Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 646
Mani Avatar asked Dec 08 '10 16:12

Mani


1 Answers

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...

like image 60
Jon Skeet Avatar answered Nov 02 '22 23:11

Jon Skeet