Wednesday, May 7, 2014

Understanding IEnumerable and IQueryable in C#

IEnumerable<T> is the base interface for collections in System.Collections.Generic namespace. IEnumerable<T> exposes the enumerator which supports iteration over a collection of a specified type. For non-generic types .NET has another interface called IEnumerable. See the difference between IEnumerable<T> and IEnumerableIEnumerable<T> has a single method GetEnumerator which you must implement when implementing the IEnumerable<T> interface. This returns a IEnumerator<T> object.



IQueryable<T> provides functionality to evaluate queries against a data source. This exists in System.Linq namespace. This inherits IEnumerable<T> interface thereby if it represents an query it can be enumerated. Enumeration forces associated expression tree to be executed.




Difference between IQueryable<T> and IEnumerable<T>
Both will give the ability for deferred execution but IQuerayable allows you to LINQ to SQL while IEnumerable does not. IEnumerable only allows LINQ to Object. IQueryable if possible will execute on database. 

AsEnumerable
Allows you to cast a specific type to its IEnumerable equivalent. In LINQ you can use this to run part of the query in SQL and the other part in memory as LINQ to Objects. One reason because when execute in memory we have more methods to work with than in database. (Ref)


AsQueryable
Converts IEnumerable to an IQueryable.

When exposing any of these interfaces to a client, the developer should design the API such that only the required details are exposed to the outside. 
Source - Stackoverflow
Also see questions for IEnumerable under stackoverflow

IEnumerable<T> has lot of extension methods. Check them here.

Provides a set of static methods for querying objects that implements IEnumerable<T>. This can be found under System.Linq namespace.

Enumerable.Empty<TResult>
Returns an empty IEnumerable<T>. 
Powered by Blogger.


Software Architect at Surge Global/ Certified Scrum Master

Experienced in Product Design, Software Engineering, Team management and Practicing Agile methodologies.

Search This Blog

Facebook