Explain in small words why IQueryable<T> is needed
-
20-08-2019 - |
Question
There's this ... MSDN page, IQueryable(Of T) Interface. Can you do a better job explaining why we need a marker interface which doesn't add any methods over IEnumerable?
Solution
It extends IEnumerable
, IQueryable
and IEnumerable<T>
. It may not have methods of its own, but it aggregates these other three interfaces as one, so you don't have to deal with them separately.
OTHER TIPS
IQueryable<T>
also extends IQueryable
. Basically it's an IQueryable
which can be enumerated in a strongly-typed way. (Both IQueryable
and IEnumerable<T>
already extend IEnumerable
, so it's not adding anything on that front.)
Now, having a strongly-typed IQueryable
allows LINQ to SQL (etc) to be strongly typed - otherwise you couldn't write Where
clauses etc without casting. The actual LINQ methods involved are in the Queryable
type, largely mirroring the Enumerable
methods but taking expression trees instead of delegates. (If you haven't used expression trees before, they're basically data structures describing the code - whereas a delegate is the code itself. So you can execute a delegate, but you can examine an expression tree to see what it would do.)
IQueryable<T>
is needed because it defines a contract that is required for a LINQ provider. Many of the extension methods available on IQueryable<T>
are designed to accept expressions rather than delegates.
This is important as a LINQ provider will need to analyze the expression tree rather than invoke a delegate.
Use IQueryable if you want to translate a linq query to an expression tree (System.Linq). From an expression tree you can easily translate your LINQ query to another language (SQL for Linq To SQL. Another classic example is Linq to Google where you want this query :
var searchResult = from result
in Google.Repository
where result.Equals("i love linq")
select result;
To translate to this url :
http://www.google.com/search?hl=en&q=i+love+linq&aq=f&oq=&aqi=g10
Then you parse the page to get the results.