Both IEnumerable and IQueryable are used for data manipulation in LINQ. As IQueryable interface derives from IEnumerable interface so that whatever IEnumerable can do, IQueryable can also do.
IEnumerable exists in System.Collections namespace and IQueryable exists in System.Linq namespace. IEnumerable does not support to custom query and IQueryable supports to custom query using CreateQuery() and Execute() methods.
IQueryable interface is used where collection is loaded with all filters(i.e. where) condition using LINQ or Entity Framework on server side.
Lets look at given below example:
IEnumerable<Customer> customer = cust.Customer;
IEnumerable<Customer> xxCityCustomer = customer.Where(c => c.City == 'xx').ToList<Customer>();
In above lines of code, all the data is fetched from database first and then it will scan the customer(s) whose city is 'xx' at the client side.
IQueryable<Customer> customer = cust.Customer;
IEnumerable<Customer> xxCityCustomer = customer.Where(c => c.City == 'xx').ToList<Customer>();
In above case, client sends the request to database where the filter is applied using SQL query. So that SELECT query is executed on database i.e. at the server side and only requested data is returned.
Clearly, we can see that the main difference between IEnumerable vs IQueryable is that where the filter logic is executed i.e. one executes on the client side and other executes on the database.
Now the question comes, when should we use IEnumerable and IQueryable in LINQ?
The answer is that IEnumerable is good choice where we are working on in-memory data collection like List, Array etc and it is suitable for LINQ to Object and LINQ to XML queries. Its best use in-memory traversal.
IQueryable is best choice where query data collection is required like remote database, service and it is suitable for LINQ to SQL queries. Its best use in paging.
IQueryable is a preferable as it executes on database side and reduces network traffic.
0 Comment(s)