2010-12-02 65 views
4

我想做一个分页样式表,但NeerDinner示例将整个数据提取到一个PaggingList类型中,并且我有超过10 000行被提取,所以我跳过了这个部分。如何在Linq中做一个简单的Count?

,所以我想出了这个查询

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); 

问题是,我怎么能得到Take部分之前结果的总数是多少?

我在想:

var t = (from p in db.JK_Prizes 
      join c in db.JK_Calendars on p.calendar_id equals c.calendar_id 
      join ch in db.JK_Challenges on c.calendar_id equals ch.calendar_id 
      join ca in db.JK_ChallengeAnswers on ch.challenge_id equals ca.challenge_id 
      join cr in db.JK_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) 

      select cr.subscriber_id) 
     .Count(); 

,但将做一遍查询...

任何人有我如何能做到这一点有效建议?

+0

可能重复:寻呼tecnique,使用取并跳过,但需要总记录也 - 如何实现此?](http://stackoverflow.com/questions/4275935/linq-paging-tecnique-using-take-and-skip-but-need-total-records-also-how-to-i) – Singleton 2010-12-02 09:32:15

+0

@Hansmukh I'米不问如何做分页......我问如何“计数”:) – balexandre 2010-12-02 09:34:02

回答

13

如果你把一个查询这样:

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

... LINQ to SQL的将是足够聪明,使这个SELECT COUNT查询,这可能是相当有效的(效率将更加依赖于条件查询)。底线是计数操作发生在数据库中,而不是LINQ代码中。

0

写下我的旧评论:好吧,我在一段时间后面临同样的问题,然后我想出了LINQ到SP =)。制作一个SP并将其放入您的实体并使用它。您可以根据您的需要获得写入Sp,例如也可以拉动整个记录列。与现在使用Wright的情况相比,它更加简单快捷。

0

你可以把计数查询逻辑,以及,见下面的示例: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); 
     }