如何在Linq中进行简单计数?

如何在Linq中进行简单计数?,linq,entity-framework,ado.net,linq-to-entities,Linq,Entity Framework,Ado.net,Linq To Entities,我想做一个分页样式的表,但NeerDinner示例将整个数据提取到一个PagingList类型中,我有10000多行要提取,所以我跳过了这一部分 所以我提出了这个问题 var r = (from p in db.Prizes join c in db.Calendars on p.calendar_id equals c.calendar_id join ch in db.Challenges on c.calendar_id equals ch.

我想做一个分页样式的表,但NeerDinner示例将整个数据提取到一个
PagingList
类型中,我有10000多行要提取,所以我跳过了这一部分

所以我提出了这个问题

var r = (from p in db.Prizes
            join c in db.Calendars on p.calendar_id equals c.calendar_id
            join ch in db.Challenges on c.calendar_id equals ch.calendar_id
            join ca in db.ChallengeAnswers on ch.challenge_id equals ca.challenge_id
            join cr in db.ChallengeResponses on ca.challenge_answer_id equals cr.challenge_answer_id

            where
                p.prize_id.Equals(prizeId)
                && ch.day >= p.from_day && ch.day <= p.to_day
                && ca.correct.Equals(true)
                && ch.day.Equals(day)

            orderby cr.Subscribers.name

            select new PossibleWinner()
            {
                Name = cr.Subscribers.name,
                Email = cr.Subscribers.email,
                SubscriberId = cr.subscriber_id,
                ChallengeDay = ch.day,
                Question = ch.question,
                Answer = ca.answer
            })
        .Skip(size * page)
        .Take(size);
但这将使整个查询重新进行


有人对我如何有效地做到这一点有什么建议吗?

写下我以前的评论:我很久以前也遇到过同样的问题,然后我想到了LINQ to SP=)。制作一个SP并将其放入您的实体中并使用它。您可以根据需要获取写SP,例如拉总记录列。与您现在使用wright时相比,它更简单、更快速。

如果您接受这样的查询:

var qry = (from x in y
           select x).Count();

…LINQ to SQL将足够聪明,使其成为
SELECT COUNT
查询,这可能相当高效(效率将更多地取决于查询中的条件)。底线是计数操作发生在数据库中,而不是在LINQ代码中。

您也可以为查询逻辑设置计数,请参见下面的示例:

 public int GetTotalCountForAllEmployeesByReportsTo(int? reportsTo, string orderBy = default(string), int startRowIndex = default(int), int maximumRows = default(int))
        {
            //Validate Input
            if (reportsTo.IsEmpty())
                return GetTotalCountForAllEmployees(orderBy, startRowIndex, maximumRows);

            return _DatabaseContext.Employees.Count(employee => reportsTo == null ? employee.ReportsTo == null : employee.ReportsTo == reportsTo);
        }

可能是@Hansmukh的副本我不是在问如何进行分页。。。我在问如何计数(这页上的答案是什么?Linq分页-如何合并总记录计数=)我知道。有一件事我想在这里指出,正如您已经说过的,您有数千条记录,那么最好在数据库端执行分页操作,而不是在实体级别执行分页操作=)性能始终很重要=)@Fasih Hansmukh谢谢!就在我读到你的评论时,我的头点击了一下。。。SP总是:)啊,我错过了“足够聪明”的部分:)
 public int GetTotalCountForAllEmployeesByReportsTo(int? reportsTo, string orderBy = default(string), int startRowIndex = default(int), int maximumRows = default(int))
        {
            //Validate Input
            if (reportsTo.IsEmpty())
                return GetTotalCountForAllEmployees(orderBy, startRowIndex, maximumRows);

            return _DatabaseContext.Employees.Count(employee => reportsTo == null ? employee.ReportsTo == null : employee.ReportsTo == reportsTo);
        }