Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IQueryable<T> vs IEnumerable<T> with Lambda, which to choose?

Tags:

lambda

c#-3.0

I do more and more exercise with Lambda but I do not figure out why sometime example use .AsQueryable(); that use the IQueryable and sometime it omit the .AsQueryable(); and use the IEnumerable.

I have read the MSDN but I do no see how "executing an expression tree" is an advantage over not.

Anyone can explain it to me?

like image 282
Patrick Desjardins Avatar asked Oct 29 '08 00:10

Patrick Desjardins


2 Answers

IQueryable implements IEnumerable, so right off the bat, with IQueryable, you can do everything that you can do with IEnumerable. IQueryables deal with converting some lambda expression into query on the underlying data source - this could be a SQL database, or an object set.

Basically, you should usually not have to care one way or the other if it is an IQueryable, or an IEnumerable.

like image 160
Andrew Theken Avatar answered Oct 14 '22 03:10

Andrew Theken


As a user, you generally shouldn't have to care, it's really about the implementor of the data source. If the data providers just implements IEnumerable, you are basically doing LINQ to objects execution, i.e. it's in memory operation on collections. IQueryable provides the data source the capability to translate the expression tree into an alternate representation for execution once the expression is executed (usually by enumeration), which is what Linq2Sql, Linq2Xml and Linq2Entities do.

The only time i can see the end user caring, is if they wish to inspect the Expression tree that would be executed, since IQueryable exposes Expression. Another use might be inspecting the Provider. But both of those scenarios should really be reserved for implementors of other query providers and want to transform the expression. The point of Linq is that you shouldn't have to care about the implementation of expression execution to be used.

like image 30
Arne Claassen Avatar answered Oct 14 '22 04:10

Arne Claassen