Friday, June 8, 2012

Anonymous Types in LINQ


In this post Anonymous Types in LINQ, we shall see how Anonymous Types are used to capture output of LINQ expressions.

To know more about Anonymous Types refer the Post Anonymous Types in .Net 3.5

One of the main uses of Anonymous Types is to capture the output of LINQ expressions, the type and structure returned by a LINQ expressions will vary based on the Expression, it will be difficult to pre-define Types to hold the results returned by LINQ expressions,

Anonymous Types comes in handy in this situation, it accepts any type of result returned by the LINQ expressions without having to pre-define them.

In the below example we use LINQ to SQL to get the details of Employees, the results of the LINQ expression is captured in an Anonymous Type variable emp.

To know more about LINQ refer the Post What is LINQ?
To know more about LINQ to SQL refer the Post LINQ to SQL

Example:

EmployeeClassesDataContext
 dbContext = newEmployeeClassesDataContext();

var emp = (from e in dbContext.Employees
            select new { e.ID, e.Name, e.Phone });

grdEmployees.DataSource = emp;
grdEmployees.DataBind();

Notice that we are binding the Anonymous Type emp directly to the GridView grdEmployees, before executing the LINQ Query the type of emp is unknown, once the Query is executed, the Type emp stores the details of the Employees returned by the LINQ query and the same is bound to the GridView.

That’s it we have seen the usage of Anonymous Types in capturing results returned by LINQ Expressions

Related Posts


Search Flipkart Products:
Flipkart.com

No comments: