views:

38

answers:

2

In the book I'm reading "Pro Linq in C# 2010" (APress, Freeman and Ratz) the author states that IQueryable will only be returned from the classes in the Linq to Sql namespace, not in the general Linq namespace. I was surprised by this, since I thought anything that had a Where on the end had to be IQueryable. Turns out I was wrong, Where is an extension of IEnumerable. Since IQueryable<T> : IEnumerable<T>, you can tack where clauses on either one.

Is the author correct?

I'm talking about the Framework classes, not any end-user-generated code.

A: 

The author is mistaken. Any class can have a method that returns IQueryable<T>.

In fact, are you sure the author leaves out LINQ to Entities? LINQ to SQL is not quite deprecated, but LINQ to Entities is where Microsoft is spending time and money, not in LINQ to SQL.

John Saunders
The OP does mention that he's talking about other Framework classes that use IQueryable, not user generated classes.
Justin Niessner
@Justin: in that case, the author is mistaken. What Framework class returns this type? Only generated code, most likely.
John Saunders
Usually `IQueryable<T>` is used with generated code but this generated code also usually just wraps or aggregates framework classes like `ObjectContext`, `ObjectSet<T>`, or `DataServiceQuery<T>` implementing or exposing `IQueryable<T>`.
Daniel Brückner
+1  A: 

There are two sets of extension methods for LINQ - one set is contained in the Enumerable class and one set in the Queryable class.

Enumerable is for LINQ to Objects working on IEnumerable<T> and using delegates as arguments. Queryable is for LINQ providers like the Entity Framework or LINQ to SQL that need to inspect and process the query and therefore use IQueryable<T> instead of IEnumerable<T>.

In the case of the both mentioned O/R mappers they have to translate the query into a SQL query. This will not work with delegates (unless one analyzes the IL code or does other insane stuff) and therfore the extension methods in Queryable are using expression trees as arguments instead of delegates.

Besides the both mentioned O/R mappers WCF Data Services (formerly ADO.NET Data Services) also use IQueryable<T> (DataServiceQuery<TElement>) and translates the queries in form of expression trees into URLs.

Daniel Brückner