Sunday, 23 April 2017

Iqueryable vs Ienumerable a comparison.

There is always a doubt in developers mind regarding usage of IQueryable and IEnumerable.

IQueryable extends IEnumerable. IQueryable should be used while working with remote databases. 

Well, here are some facts which can help resolving your doubt and can strengthen your decision-making as which one to use.

Some important points about Ienumberable<T>
  • It's read-only.
  • Iterates only in forward direction.
  • Doesn't supports adding or removing objects.
  • It's a base interface for any generic collection
When to use IEnumberable:
  • Working with read-only collection
  • Need to read objects in the forward direction.
  • Want to iterate collection using for-each.

Some important points about IQueryable<T>
  • It implements IEnumerable so the results can be iterated using for-each.
  • Best suited for querying against the remote data source.
When to use IQueryable
  • your data source is queryable.
  • Data needs to be applied 
  • The deferred way is needed to load the data.

System.Collections Namespace
System.Linq Namespace
Derives from
No base interface
Derives from IEnumerable
Not Supported
How does it work
While querying data from the database, IEnumerable executes a select query on the server side, load data in-memory on the client side and then filter data. Hence does more work and becomes slow.
While querying data from the database, IQueryable executes a select query on the server side with all filters. Hence does less work and becomes fast.
Suitable for
LINQ to Object and LINQ to XML queries
LINQ to SQL queries
Custom Query
Doesn’t support
Supports using CreateQuery and Execute methods
Extension method
Extension methods supported in IEnumerable takes functional objects.
Extension methods supported in IEnumerable takes expression objects, i.e., expression tree.
When to use
When querying data from in-memory collections like ListArray, etc.
When querying data from out-memory (like remote database, service) collections.
Best Uses
In-memory traversal
Table from code project