IEnumerable VS IQueryable
In LINQ to query data from database and
collections, we use IEnumerable and IQueryable for data manipulation. IEnumerable
is inherited by IQueryable, Hence IQueryable has all the features of
IEnumerable and except this, it has its own features.
|
IEnumerable |
IQueryable
|
Namespace
|
System.Collections Namespace
|
System.Linq Namespace
|
Derives
from
|
No base interface
|
Derives from IEnumerable
|
Supported
|
Supported
|
|
Not Supported
|
Supported
|
|
How
does it work
|
While querying data from database, IEnumerable executes select query on server side, load
data in-memory on client side and then filter data. Hence does more work and
becomes slow.
|
While querying data from database, IQueryable executes select query on server side with all
filters. Hence does less work and becomes fast.
|
Suitable
for
|
LINQ to Object and LINQ to XML queries
|
LINQ to SQL queries
|
Custom
Query
|
Doesn’t support
|
Supports using CreateQuery and Executemethods
|
Extension
method
parameter |
Extension methods supported in IEnumerable takes
functional objects.
|
Extension methods supported in IEnumerable takes
expression objects, i.e., expression tree.
|
When
to use
|
When querying data from in-memory collections like List, Array, etc.
|
When querying data from out-memory (like remote database, service)
collections.
|
Best
Uses
|
In-memory traversal
|
Paging
|
|
1. IEnumerable<Employee> list = dc.Employees.Where(p => p.Name.StartsWith("S"));
2. list = list.Take<Employee>(10);
1. SELECT [t0].[EmpID], [t0].[EmpName], [t0].[Salary] FROM [Employee] AS [t0] 2. WHERE [t0].[EmpName] LIKE @p0
Notice that in this query "top
10" is missing since
IEnumerable filters records on client side
|
1. IQueryable<Employee> list = dc.Employees.Where(p => p.Name.StartsWith("S"));
2. list = list.Take<Employee>(10);
1. SELECT TOP 10 [t0].[EmpID], [t0].[EmpName], [t0].[Salary] FROM [Employee] AS [t0]
2. WHERE [t0].[EmpName] LIKE @p0
Notice that in
this query "top 10" is exist since IQueryable
executes query in SQL server with all filters.
|
No comments:
Post a Comment