tags:

views:

1840

answers:

3

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?

+6  A: 

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.

Andrew Theken
+5  A: 

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.

Arne Claassen
+1  A: 

I agree with Arne Claassen, there are cases when you need to think about the underlying implmentatoin provided by the data sources. For example check this blog post which shows how the SQL generated by IEnumerable and IQueryable are different in certain scenarios.

Shreedhar