Difference between IEnumerable and IQueryable
By TSN ...
Here is the small sample that explains the difference between IEnumerable<T> and IQueryable<T>.
When we perform the IEnumerable <T> the data is first loaded into the memory
and then the conditional Query is then performed on it, where as in IQueryable
the query is executed in the database if possible .
consider the example..
NorthwindEntities ne = new NorthwindEntities();
protected void Page_Load(object sender, EventArgs e)
{
IQueryable<Employee> emp = ne.Employees.Take(10);
List<Employee> empList = emp.ToList();
}
When you look at the emp when you are in debug mode you could see in the LOCALS
window the emp is value is
emp -- {System.Data.Objects.ObjectQuery<JsonApplication2.Employee>}
this simply specifies it the just the Query and when you execute emp.ToList() , then the data is retrieved and assigned to empList.
and major advantage of IQuerayable is that the query is Executed in the database
if possible . So most of the data is filtered there itself.
Coming to the IEnumerable<T>
public partial class TabLazyLoadingSample : System.Web.UI.Page
{
NorthwindEntities ne = new NorthwindEntities();
protected void Page_Load(object sender, EventArgs e)
{
IEnumerable<Employee> emp = ne.Employees.Take(10);
List<Employee> empList = emp.ToList();
}
}
In this case the main Query is loaded into the memory and then there the execution
for ISActive Employees is performed.
This is quite an important difference, and working on IQueryable<T> 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<T> will
cause all of your rows to be loaded in memory.
Related FAQs
The Sample shows a Functions to repalce a character in the string .
Multiple Order By Using Linq i.e using Order by with more than one Variable...
For the sample i have taken theis generic list of type Player and Player_Data , which i will use this Lists as collections and perform the joins operations using Linq.
Difference between IEnumerable and IQueryable (1060 Views)