Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does a LINQ expression know that Where() comes before Select()?

Tags:

c#

.net

linq

I'm trying to create a LINQ provider. I'm using the guide LINQ: Building an IQueryable provider series, and I have added the code up to LINQ: Building an IQueryable Provider - Part IV.

I am getting a feel of how it is working and the idea behind it. Now I'm stuck on a problem, which isn't a code problem but more about the understanding.

I'm firing off this statement:

QueryProvider provider = new DbQueryProvider();
Query<Customer> customers = new Query<Customer>(provider);

int i = 3;
var newLinqCustomer = customers.Select(c => new { c.Id, c.Name}).Where(p => p.Id == 2 | p.Id == i).ToList();

Somehow the code, or expression, knows that the Where comes before the Select. But how and where?

There is no way in the code that sorts the expression, in fact the ToString() in debug mode, shows that the Select comes before the Where.

I was trying to make the code fail. Normal I did the Where first and then the Select.

So how does the expression sort this? I have not done any change to the code in the guide.

like image 499
Dennis Larsen Avatar asked Jul 23 '11 17:07

Dennis Larsen


1 Answers

The expressions are "interpreted", "translated" or "executed" in the order you write them - so the Where does not come before the Select


If you execute:

        var newLinqCustomer = customers.Select(c => new { c.Id, c.Name})
                                       .Where(p => p.Id == 2 | p.Id == i).ToList();

Then the Where is executed on the IEnumerable or IQueryable of the anonymous type.


If you execute:

        var newLinqCustomer = customers.Where(p => p.Id == 2 | p.Id == i)
                                       .Select(c => new { c.Id, c.Name}).ToList();

Then the Where is executed on the IEnumerable or IQueryable of the customer type.


The only thing I can think of is that maybe you're seeing some generated SQL where the SELECT and WHERE have been reordered? In which case I'd guess that there's an optimisation step somewhere in the (e.g.) LINQ to SQL provider that takes SELECT Id, Name FROM (SELECT Id, Name FROM Customer WHERE Id=2 || Id=@i) and converts it to SELECT Id, Name FROM Customer WHERE Id=2 || Id=@i - but this must be a provider specific optimisation.

like image 109
Stuart Avatar answered Sep 28 '22 02:09

Stuart