Basically I want to know if the two statements below are ultimately exactly the same. The NerdDinner tutorial states that IQueryable<> objects won’t query the database until we attempt to access/iterate over the data or call ToList on it. So aside from returning the same exact items do the two statements below also PERFORM the same as far as querying the database is concerned? If I had a million records, would one be better than the other?
I have the following statement:
return from party in entities.Parties
where party.PartyDate > DateTime.Now
orderby party.PartyDate
select party;
is that the same as:
return entities.Parties.Where(p => p.PartyDate > DateTime.Now);
They will perform exactly the same, yes – aside from the ordering. With a very slight change, they will compile into exactly the same code:
Note that as well as adding the
OrderBy, I’ve also changed the name of the lambda expression parameter name to match that in the query expression.Effectively the compiler transforms the first block into the second block before applying all the normal compilation steps. You can think of query expression support as being a bit like a preprocessor step.
I wrote about this in more detail in my Edulinq blog series, in Part 41: How Query Expressions Work.