Monday, June 23, 2014

IEnumerable vs IQueryable

Many  developers gets confused between IEnumerable and IQueryable. When it comes to writing code, both looks very similar. However there are many difference between them which needs to be taken care of while writing code. Both have some intended usability scenarios for which they are made.
Below lists the differences between them based on their properties :
IEnumerable IQueryable
NamespaceSystem.Collections NamespaceSystem.Linq Namespace
Derives fromNo base interfaceDerives from IEnumerable
Deferred ExecutionSupportedSupported
Lazy LoadingNot SupportedSupported
How does it workWhile querying data from database, IEnumerable execute select query on server side, load data in-memory on client side and then filter data. Hence does more work and becomes slow.While querying data from database, IQueryable execute select query on server side with all filters. Hence does less work and becomes fast.
Suitable forLINQ to Object and LINQ to XML queries.LINQ to SQL queries.
Custom QueryDoesn’t supports.Supports using CreateQuery and Execute methods.
Extension mehtod
parameter
Extension methods supported in IEnumerable takes functional objects.Extension methods supported in IEnumerable takes expression objects i.e. expression tree.
When to usewhen querying data from in-memory collections like List, Array etc.when querying data from out-memory (like remote database, service) collections.
Best UsesIn-memory traversalPaging

The difference is that IQueryable is the interface that allows LINQ-to-SQL (LINQ.-to-anything really) to work. So if you further refine your query on an IQueryable, that query will be executed in the database, if possible.
For the IEnumerable case, it will be LINQ-to-object, meaning that all objects matching the original query will have to be loaded into memory from the database.
In code:
IQueryable<Customer> custs = ...;
// Later on...
var goldCustomers = custs.Where(c => c.IsGold);
That code will execute SQL to only select gold customers. The following code, on the other hand, will execute the original query in the database, then filtering out the non-gold customers in the memory:
IEnumerable<Customer> custs = ...;
// Later on...
var goldCustomers = custs.Where(c => c.IsGold);
This is quite an important difference, and working on IQueryable can in many cases save you from returning too many rows from the database. Another prime example is doing paging: If you use Take and Skip on IQueryable, you will only get the number of rows requested; doing that on an IEnumerable will cause all of your rows to be loaded in memory.

No comments: