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.
The first version wouldn’t even compile – because the return value of
Takeis anIEnumerable<T>, not aList<T>. So you’d need it to be: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 callingEnumerable.ToList()which will fetch all the entries. In other words, the call toToListdoesn’t participate in SQL translation, whereasTakedoes.Also note that using a query expression here doesn’t make much sense either. I’d write it as:
Mind you, you may want an
OrderBycall – otherwise it’ll just take the first 10 entries it finds, which may not be the latest ones…