Thursday 28 March 2013

IEnumerable and IQueryable

IEnumerable is inherited by IQueryable, hence it has all the features of it and except this, it has its own features

IEnumerable<T> is great for working with sequences that are iterated in-memory, but IQueryable<T> allows for out-of memory things like a remote data source, such as a database or web service.
 
 
IEnumerable is refering to a collection but IQueryable is just a query and it will be generated inside a Expression Tree.we will run this query to get data from database.

The major difference is that IEnumerable will enumerate all elements, while IQueryable will enumerate elements (or even do other things) based on a query. In the case of the IQueryable, the LINQ query gets used by IQueryProvider which must be interpreted or compiled in order to get the result. I.e., the extension methods defined for IQueryable take Expression objects instead of Func objects (which is what IEnumerable uses), meaning the delegate it receives is an expression tree instead of a method to invoke.

for example:
IEnumerable ->

IEnumerable<Employee> list = dc.Employees.Where(p => p.Name.StartsWith("S"));

The above statement represents the below query:

SELECT [t0].[EmpID], [t0].[EmpName], [t0].[Salary] FROM [Employee] AS [t0WHERE [t0].[EmpName] LIKE @p0

IQueryable->

IQueryable<Employee> list = dc.Employees.Where(p => p.Name.StartsWith("S"));
list = list.Take<Employee>(10); 
The above statement represents the below query:

SELECT TOP 10 [t0].[EmpID], [t0].[EmpName], [t0].[Salary] FROM [Employee] AS [t0]
WHERE [t0].[EmpName] LIKE @p0