Var Type with LINQ
Since Var is anonymous types, hence use it whenever you don't know the type of output or it is anonymous. In LINQ, suppose you are joining two tables and retrieving data from both the tables then the result will be an Anonymous type.In above query, result is coming from both the tables so use Var type.
- var q =(from e in tblEmployee
- join d in tblDept on e.DeptID equals d.DeptID
- select new
- {
- e.EmpID,
- e.FirstName,
- d.DeptName,
- });
In above query, result is coming only from single table but we are combining the employee's FirstName and LastName to new type FullName that is annonymous type so use Var type. Hence use Var type when you want to make a "custom" type on the fly.
- var q =(from e in tblEmployee where e.City=="Delhi" select new {
- e.EmpID,
- FullName=e.FirstName+" "+e.LastName,
- e.Salary
- });
More over Var acts like as IQueryable since it execute select query on server side with all filters. Refer below examples for explanation.
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 :
Notice that in this query "top 10" is missing since IEnumerable filters records on client side
- SELECT [t0].[EmpID], [t0].[EmpName], [t0].[Salary] FROM [Employee] AS [t0]
- WHERE [t0].[EmpName] LIKE @p0
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 :
Notice that in this query "top 10" is exist since var is a IQueryable type that executes query in SQL server with all filters.
- SELECT TOP 10 [t0].[EmpID], [t0].[EmpName], [t0].[Salary] FROM [Employee]
- AS [t0] WHERE [t0].[EmpName] LIKE @p0
IEnumerable Type with LINQ
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);
Note
- In LINQ query, use Var type when you want to make a "custom" type on the fly.
- In LINQ query, use IEnumerable when you already know the type of query result.
- In LINQ query, Var is also good for remote collection since it behaves like IQuerable.
- IEnumerable is good for in-memory collection.
No comments:
Post a Comment