Difference between Var and IEnumerable
-
S.No
VarIEnumerable1When to use ?
Use Var type when we want to make a "custom" type on the fly.When to use ?
Use IEnumerable when we already know the type of query result.2Good for:
Var is also good for remote collection.Good for:
IEnumerable is good for in-memory collection.
IEnumerable Example
MyDataContext dc = new MyDataContext ();
IEnumerable<Employee>
list = dc.Employees.Where(p => p.Name.StartsWith("S"));
list
= list.Take<Employee>(10);
Generated SQL statements of above query will be :
SELECT [t0].[EmpID], [t0].[EmpName], [t0].[Salary] FROM [Employee] AS [t0] WHERE [t0].[EmpName] LIKE @p0Notice that in this query "top 10" is missing since IEnumerable filters records on client side
Var Example
MyDataContext dc = new MyDataContext ();
var
list = dc.Employees.Where(p => p.Name.StartsWith("S"));
list
= list.Take<Employee>(10);
Generated SQL statements of above query will be :
SELECT TOP 10 [t0].[EmpID], [t0].[EmpName], [t0].[Salary] FROM [Employee] AS [t0] WHERE [t0].[EmpName] LIKE @p0Notice that in this query "top 10" is exist since var is a IQueryable type that executes query in SQL server with all filters.
IEnumerable Type
IEnumerable is a forward only collection and is useful when we already know the type of query result. In below query the result will be a list of employee that can be mapped (type cast) to employee table.IEnumerable<tblEmployee> lst =(from e in tblEmployee
where
e.City=="Delhi"
select
e);
Reference:
No comments:
Post a Comment