Saturday, June 2, 2012

IQueryable vs. IEnumerable in terms of LINQ to SQL queries

IQueryable inherited IEnumerable, so it obviously get all the functionality IEnumerable has. The working style of both is still different. There are still lot many differences exists between the two which impact the decision we took in usage of either one. Both of these suits for particular scenarios. Following are some differences using which we can took decision to use anyone of these optimally.
ParameterIQueryableIEnumerable
Extension MethodsExtension methods defined for IQueryable take expression objects. Means, the delegate IQueryable extension methods receives is an expression tree.Extension methods defined for IEnumerable take functional objects. Means, the delegate IEnumerable extension methods receives is a method to invoke.
Great ForIQueryable allows out-of-memory things like remote data source operations, such as working with database or web service.IEnumerable is great for working with sequences (in-memory collections), that are iterated in-memory.
Supported QueriesIQueryable supports LINQ to SQL queries.IEnumerable supports LINQ to Object and LINQ to XML queries.
Deferred ExecutionIQueryable supports lazy loading (Suited for scenarios like paging and composition based queries).IEnumerable lost lazy loadnig ability on the external provider.
Moving between itemsIQueryable provides many methods to move between the items.IEnumerable doesn’t have the concept of moving between items, it is forward only collection.
Filtering MechanismIQueryable executes query on server side along with all the filters applied.IEnumerable executes select query on server side, loads data in-memory and then executes filter at client side.
CreateQuery and Execute MethodsIQueryable has these two additional methods. Both takes expression as input. CreateQuery returns IQueryable representing expression tree. Execute returns result of the query.NA
Custom Querying CapabilityIQueryable provides additional functionality to implement custom querying with LINQ.IEnumerable does not have custom querying capability.
Performance PerspectiveIQueryable gives best performance when used for out-of-memory data store operations (that is external to .NET CLR memory).IEnumerable gives best performance when used to manipulate in-memory collections.


IEnumerable: IEnumerable is best suitable for working with in-memory collection. IEnumerable doesn’t move between items, it is forward only collection.
IQueryable: IQueryable best suits for remote data source, like a database or web service. IQueryable is a very powerful feature that enables a variety of interesting deferred execution scenarios (like paging and composition based queries).


So when you have to simply iterate through the in-memory collection, use IEnumerable, if you need to do any manipulation with the collection like Dataset and other data sources, use IQueryable

No comments:

Post a Comment