开发者

Using Count with Take with LINQ

开发者 https://www.devze.com 2022-12-30 09:56 出处:网络
Is there a w开发者_运维百科ay to get the whole count when using the Take operator?You can do both.

Is there a w开发者_运维百科ay to get the whole count when using the Take operator?


You can do both.

IEnumerable<T> query = ...complicated query;
int c = query.Count();
query = query.Take(n);

Just execute the count before the take. this will cause the query to be executed twice, but i believe that that is unavoidable.

if this is in a Linq2SQL context, as your comment implies then this will in fact query the database twice. As far as lazy loading goes though it will depend on how the result of the query is actually used.

For example: if you have two tables say Product and ProductVersion where each Product has multiple ProductVersions associated via a foreign key.

if this is your query:

var query = db.Products.Where(p => complicated condition).OrderBy(p => p.Name).ThenBy(...).Select(p => p);

where you are just selecting Products but after executing the query:

var results = query.ToList();//forces query execution
results[0].ProductVersions;//<-- Lazy loading occurs

if you reference any foreign key or related object that was not part of the original query then it will be lazy loaded in. In your case, the count will not cause any lazy loading because it is simply returning an int. but depending on what you actually do with the result of the Take() you may or may not have Lazy loading occur. Sometimes it can be difficult to tell if you have LazyLoading ocurring, to check you should log your queries using the DataContext.Log property.


The easiest way would be to just do a Count of the query, and then do Take:

var q = ...;
var count = q.Count();
var result = q.Take(...);


It is possible to do this in a single Linq-to-SQL query (where only one SQL statement will be executed). The generated SQL does look unpleasant though, so your performance may vary.

If this is your query:

IQueryable<Person> yourQuery = People
    .Where(x => /* complicated query .. */);

You can append the following to it:

var result = yourQuery
    .GroupBy (x => true) // This will match all of the rows from your query ..
    .Select (g => new {
        // .. so 'g', the group, will then contain all of the rows from your query.
        CountAll = g.Count(),
        TakeFive = g.Take(5),
        // We could also query for a max value.
        MaxAgeFromAll = g.Max(x => x.PersonAge)
    })
    .FirstOrDefault();

Which will let you access your data like so:

// Check that result is not null before access.
// If there are no records to find, then 'result' will return null (because of the grouping)
if(result != null) {

    var count = result.CountAll;

    var firstFiveRows = result.TakeFive;

    var maxPersonAge = result.MaxAgeFromAll;

}
0

精彩评论

暂无评论...
验证码 换一张
取 消