IEnumerable Vs IQueryable

posted on October 4th, 2013

Out of the box LINQ supports two interfaces: IEnumerable and IQueryable. So what is the difference between these two interfaces? Should one be used over the other? This post will briefly answer these questions and provide code to make the difference between the two clear.

Both Have Deferred Execution

Both interfaces won't resolve their LINQ queries until the results are needed.

Both Will Always Return The Same Results

Given identical input and LINQ statements IQueryable and IEnumerable will always return the same results.

IQueryable Executes All LINQ Statements In One Go

The IQueryable interface is fundamentally made of two parts: a data source and an expression tree. Every time a LINQ statement is placed on an IQueryable, the statement is added to the interface's expression tree. Once the LINQ query is resolved the cumulative expression of all LINQ statements will be executed once on the data source. This allows functionality like LINQ to SQL to write complete SQL queries.

IEnumerable Executes All LINQ Statements One At A Time

The IEnumerable interface is only made up of one part: a data source. Every time a LINQ statement is placed on an IEnumerable that Statement is stored with the current state of the IEnumerable. Once the LINQ query on IEnumerable is resolved each LINQ statement is executed in order, the output of each statement is used as the input for the next statement.

Sources

Sample Code