views:

290

answers:

3

I'm kinda confused what the IQueryable interface actually represents.

The MSDN documentation for IQueryable says: "Provides functionality to evaluate queries against a specific data source."

The documentation for IQueryProvider says: "Defines methods to create and execute queries that are described by an IQueryable object."

The name and the documentation summary suggest that it is an object/data store which can be queried. The second quote and the fact the ObjectQuery class from the Entity Framework implements IQueryable suggest it is a query which can be executed.

Did I misunderstood something or is it really kinda fuzzy?

+2  A: 

An IQueryable represents the query itself. It will have a data source associated with it, but it isn't the data store itself. In particular, it won't usually have all the data in memory.

You can possibly think of it a bit like a SqlCommand object - it's got the query, it knows what to ask for the data, but it doesn't contain the data istelf.

Jon Skeet
But why is it called IQueryable then? Thats the main source of my confusion. IQuery would be a more appropriate name then.
Albic
@Albic: I don't know on the naming front, I'm afraid.
Jon Skeet
+1  A: 

An IQueryable represents a source against which queries can be executed. It could be a representation of a table on a SQL server or an in-memory collection of objects.

An IQueryProvider represents an object that can create and execute queries as represented by expression trees. The LINQ-to-SQL query provider, for example, will take expression trees and return an IQueryable that allows you to enumerate over (to get the results) or further refine (by composing queries) before enumerating over.

There's a very nice walkthrough on MSDN on creating your own IQueryProvider. I think that if you do this walkthrough you'll have a much better understanding.

Jason
And the Expression represents the query itself, right? The IQueryProvider.CreateQuery<T> method on the other hand returns an IQueryable<T>. This inconsistent naming confuses me.
Albic
+1  A: 

An IQueryable represents two (arguably very distinct) things. It represents a query, in the form of a reference to an expression tree describing some code, and a data source, in the form of a reference to a "provider" which knows how to execute the query.

I think the source your confusion comes from the fact that the docs can only talk about the methods IQueryable actually defines. Most of the power of IQueryable comes from the implementation of its associated extension methods defined in the Queryable class, but they are not strictly part of the IQueryable interface.

Interesting!

Update: Rereading your question, another useful insight is that a query is itself queryable. This is key to enabling compositionality in LINQ. So an IQueryable is a query, and it is queryable - so there's no contradiction in the type name.

Pete Montgomery