Monday 25 January 2016

IEnumerable vs IQueryable in c#?

What is IEnumerable and IQueryable in c#?

Both are the collection interface that is use to itrate the collection in forward manners. These are the proints that we ned to keep in our mind while implementing IEnumerable or IQueryable.

 Differences:

  •  IEnumerable is exists in System.Collection, where as IQueryable exists in System.Linq.
  •  IEnumerable is best over in-memory collection like List, Array etc, where as IQueryable is best over out-memory collections like database and services.
  •  IEnumerable is best for Linq to XML, IQueryable best for Linq to SQL.
  •  IEnumerable has no methods like create, add and more it's read only can't customized, where as IQueryable has CreateQuery and Execute methods can customized.
  •  IEnumerable doesn't support lazy loading, IQueryable support lazy loading.
  •  IEnumerable execute in-memory after formulating query strecture, where as IQueryable formulate complete query and executes on remote server.

Example:-
IEnumerable<>
DBContext dc = new DBContext ();
IEnumerable<Employee> list = dc.Employees.Where(p => p.Name.StartsWith("R"));
list = list.Take<Employee>(10);
SELECT [t0].[EmpID], [t0].[EmpName] FROM [Employee] AS [t0] WHERE [t0].[EmpName] LIKE @p0
Now filter 10 records in client memory.

IQueryable<>
DBContext dc = new DBContext ();
IQueryable<Employee> list = dc.Employees.Where(p => p.Name.StartsWith("R"));
list = list.Take<Employee>(10);
SELECT TOP 10 [t0].[EmpID], [t0].[EmpName] FROM [Employee] AS [t0] WHERE [t0].[EmpName] LIKE @p0