简体   繁体   中英

C# LINQ: does the linq query only return deferred enumerable?

I have a method

GetPostsByCategory

I can do it like the approach A to re-use what I have

A

public IEnumerable<Post> GetPostsByApartmentId(
    string apartmentId,
    int pageIndex,
    int pageSize,
    int max = 50)
{
    var itemsPerPage = Math.Max(pageSize, max);
    return _context.Post
        .Where(p => p.ApartmentId == apartmentId && !p.Disabled)
        .Skip((pageIndex - 1) * itemsPerPage)
        .Take(itemsPerPage);
}

public IEnumerable<Post> GetPostsByCategory(
    string categoryId,
    string apartmentId,
    int pageIndex,
    int pageSize,
    int max = 50)
{
    return GetPostsByApartmentId(apartmentId, pageIndex, pageSize, max)
        .Where(p => p.CategoryId == categoryId);
}

But, I am concerned about the performance for the A, so here is the approach B

public IEnumerable<Post> GetPostsByCategory(
    string categoryId,
    string apartmentId,
    int pageIndex,
    int pageSize,
    int max)
{
    var itemsPerPage = Math.Max(pageSize, max);
    return _context.Post
        .Where(p => p.ApartmentId == apartmentId && !p.Disabled && p.CategoryId == categoryId)
        .Skip((pageIndex - 1) * itemsPerPage)
        .Take(itemsPerPage);
}

However, I remember I read some articles saying: the Lambda Expression(or LINQ, can't remember) does not really execute the query, it just constructs the query and it only gets executed when it is needed or by calling something like ToList(). So if this is the case, then both A and B should be same. Can some one please confirm this?

Option B would be fast, as it is getting filtered data in single go.

A will retrieve all data based on condition and then it will filter based on category. There is possibility that it may endup retrieve unintended data.

Edit:

It would be interesting in case of Stored procedure how it will behaves.

If you have access to profiler then it would be easy to check what is final SQL statement reches to sqlserver for execution.

I'm not very much sure about, internal mechanism of entity framework.

But from your code I think that to achieve same thing compiler/EF have to do something behind the scene twice.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM