LINQ ToList().Take(10) vs Take(10).ToList() which one generates more efficient query

c#, linq, linq-to-sql

Solution

The first version wouldn't even compile - because the return value of `Take` is an `IEnumerable<T>`, not a `List<T>`. So you'd need it to be:

public List<Log> GetLatestLogEntries()
{
    var logEntries = from entry in db.Logs
                 select entry;
    return logEntries.ToList().Take(10).ToList();
}

That would fetch all the data from the database and convert it to a list, then take the first 10 entries, then convert it to a list again.

Getting the `Take(10)` to occur in the database (i.e. the second form) certainly looks a heck of a lot cheaper to me...

Note that there's no `Queryable.ToList()` method - you'll end up calling `Enumerable.ToList()` which will fetch all the entries. In other words, the call to `ToList` doesn't participate in SQL translation, whereas `Take` does.

Also note that using a query expression here doesn't make much sense either. I'd write it as:

public List<Log> GetLatestLogEntries()
{
    return db.Log.Take(10).ToList();
}

Mind you, you may want an `OrderBy` call - otherwise it'll just take the first 10 entries it finds, which may not be the latest ones...

Problem

Given the following LINQ Statement(s), which will be more efficient? ONE: ``` public List<Log> GetLatestLogEntries() { var logEntries = from entry in db.Logs select entry; return logEntries.ToList().Take(10); } ``` TWO: ``` public List<Log> GetLatestLogEntries() { var logEntries = from entry in db.Logs select entry; return logEntries.Take(10).ToList(); } ``` I am aware that .ToList() executes the query immediately.

Original source