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:
Thanks again!
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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With