Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequence of LINQ method of any importance?

Just wondering, does it matter in which sequence the LINQ methods are added?

Eg.

using(MyDataContext context = new MyDataContext())
{
   var user = context.Users
                     .Where(u => u.UserName.StartsWith("t"))
                     .OrderByDescending(u => u.CreatedDate)
                     .FirstOrDefault();
}

and this are completely the same?

using(MyDataContext context = new MyDataContext())
{
   var user = context.Users
                     .OrderByDescending(u => u.CreatedDate)
                     .Where(u => u.UserName.StartsWith("t"))
                     .FirstOrDefault();
}

Of course I can have all methods tested one by one, but I'd like to have some general idea about the logic.

So:

  • Other than methods like FirstOrDefault(), ToList() and other methods that really trigger the execution is it of any importance to have some type of order in the LINQ statement?

Thanks again!

like image 492
Herman Cordes Avatar asked Dec 16 '10 08:12

Herman Cordes


2 Answers

In LINQ to SQL, I'd expect these two queries to be the same - they should end up with the same query plan, at least, even if not the exact same SQL.

In LINQ to Objects, they would behave very differently. Imagine you had a million users, but only two of them had usernames starting with "t". in the first form, you'd be filtering and then sorting those two users... in the second form, it would need to sort everything before it started filtering.

Of course there are other situations where the ordering matters too - in particular, if you have a Select half way down and then a Where clause, then you'll be filtering on different things. Imagine this:

var query = Enumerable.Range(-20, 30)
                      .Select(x => -x)
                      .Where(x => x > 5);

vs

var query = Enumerable.Range(-20, 30)
                      .Where(x => x > 5)
                      .Select(x => -x);

In the first example the results will be "20, 19, 18, ... 6" whereas in the second query the results will be "-6, -7, -8, -9, -10". Hugely different!

like image 128
Jon Skeet Avatar answered Sep 17 '22 12:09

Jon Skeet


It depends on which LINQ provider you're using. In the case of LINQ to SQL, the expression tree will parse down to the same underlying SQL query in either case. However, with a less intelligent provider you might find that doing the .Where() first would be more efficient, as it would filter your objects before sorting them, which could make quite a difference with a large number of entities.

like image 27
MarkXA Avatar answered Sep 17 '22 12:09

MarkXA