Introduction
One of the most exciting features of .NET 3.5 would be LINQ(Language Integrated Query), a set of language extensions that allow you to perform queries without leaving the comfort of the C# language.
These query expressions can select, filter, sort, group and transform data. Different LINQ extensions allow you to use the same query expressions with different data sources.
LINQ is a deeply integrated part of .NET 3.5, the C# 2008 language and Visual Basic 2008. However, it isn't an ASP.NET specific feature and can be used equally well in any type of .NET application;
The most common use of LINQ is related to data retrieval such as LINQ to SQL which allows you to query SQL Server database without writing data access code.LINQ to XML allows you to read an XML File without using .NET specialized XML classes.
LINQ Basics
The easiest way to learn LINQ is by example. Below is the sample code of how you normally retrieve and manipulate the data using ordinary .NET code
Sample code on how to retrieve the list of the employees that have First Name start with H.
List<EmployeeDetails> lstEmployee = db.GetEmployees();
List<EmployeeDetails> matches = new List<EmployeeDetails>();
foreach(EmployeeDetails oEmployee in lstEmployee)
{
if(oEmployee.FirstName.StartsWith("H"))
{
matches.Add(oEmployee);
}
}
gridEmployees.DataSource = matches;
gridEmployees.DataBind();
Sample code on doing the same thing by using LINQ
List<EmployeeDetails> lstEmployee = db.GetEmployees();
IEnumerable<EmployeeDetails> matches;
matches = from oEmployee in lstEmployee
where oEmployee.FirstName.StartsWith("H")
select oEmployee;
gridEmployees.DataSource = matches;
gridEmployees.DataBind();
As you can see the syntax for LINQ is quite easy to understand and similar to SQL language. It is designed to be like this. This makes life of developers easy and cut your learning curve.
LINQ Expressions
Below, I would explain the basic syntax of LINQ. As you have noticed above, LINQ syntax is similar to SQL queries. LINQ expressions must have a from clause that indicates the datasource and a select clause that indicates the data you want to retrieve.
Projection using LINQ IEnumerable<STRING> matches;
matches = from oEmployee in employees
select employee.FirstName;
Filtering using LINQ
IEnumerable <EmployeeDetails> matches;
matches = from oEmployee in lstEmployees
orderby oEmployee.LastName,oEmployee.FirstName
select oEmployee;
Another Example for Filtering using LINQ
IEnumerable<PRODUCT> matches;
matches = from product in products
where product.Price > 400 && product.Name.StartsWith("D")
select product;
The where clause takes a conditional expression that's evaluated for each item.If it's true, the item is included in the result. However LINQ keeps the same deferred execution model which means the where clause isn't evaluated until you actually attempt to iterate the results.
You can also combine multiple conditional expressions with the and (&&) and or (||) operators.
One interesting feature of LINQ expressions is that you can easily call your own methods inline.
For example you could create a function named
TestEmployee() that examines an Employee and returns true or false based on whether you include it in the results.
private bool IsGoodEmployee(Employee oEmployee) {
return oEmployee.FirstName.StartsWith("D");
}
You could then use the
IsGoodEmployee Method like this
IEnumerable<EMPLOYEEDETAILS> matches;
matches = from oEmployee in employees
where IsGoodEmployee(oEmployee)
select oEmployee;
Sorting using LINQ
IEnumerable <EMPLOYEEDETAILS> matches;
matches = from oEmployee in employees
orderby oEmployee.LastName
select oEmployee;
Note:
Sorting is supported on any types of that implement
IComparable, which includes most core .NET data types like (numeric data, dates and strings).
Grouping and Aggregation
In SQL, if you would like to group the result based on certain criteria, you would normally use the keyword GROUP BY. In LINQ you can do the same thing also.
Below is the syntax
var matches = from oEmployee in employees
group oEmployee by oEmployee.FamilyName into g
select g.Key;
var matches = from oEmployee in employees
group oEmployee by oEmployee.FamilyName into g
select new {FamilyName= g.Key, Employees = g.Count()};
The result shown if we bind into datagrid will be like this
FamilyName EmployeesBlack 2
Smith 4
Green 5
Along with
Count(), LINQ also defines more powerful extension methods that you want to use in grouping scenarios such as the aggregation functions
Max().
Min() and
Average(). The LINQ expression that use this methods are bit complicated because they also use another C# features known as Lambda Expression which allows you to supply additional parameters to the extension method.
Example Below
var categories = from p in products
group p by p.Category into g
select new { Category = g.Key,
MaximumPrice = g.Max(p => p.UnitPrice),
MinimumPrice = g.Min(p => p.UnitPrice),
AveragePrice = g.Average(p => p.UnitPrice) };
LINQ to DataSet
As you have probably know that the DataTable.Select() method to extract a few records that interest you from a DataTable using a SQL like filter expression. Although the Select () method work perfectly well, it has a few obvious limitations. First it's string based which means it is subject to errors that won't be caught on compile time.It is also limited to the filtering and doesn't provide the other features that LINQ operators offer such as sorting, grouping and projections.
Below is the sample code on how you use LINQ to query the DataSet
var matches = from oEmployee in ds.Tables["Employees"].AsEnumerable()
where oEmployee.Field<STRING>("LastName").StartsWith("D")
select new {First = oEmployee.Field<STRING>("FirstName"),
Last = oEmployee.Field<STRING>("LastName")};
datagrid1.DataSource = matches;
datagrid1.DataBind();
Typed Data Sets
If you use Typed DataSets, then you can rewrite the expression in previous example in much simpler code
var matches = from oEmployee in ds.Employees
where oEmployee.LastName.StartsWith("D")
select new {First = oEmployee.FirstName,
Last = oEmployee.LastName};
LINQ to SQL
For many ASP.NET developers, LINQ to SQL is the most exciting part of LINQ. It allows you to use ordinary LINQ expressions like the ones you already seen to query data in SQL Server database. It performs the magic by translating LINQ expressions into SQL queries behind the scenes. It executes these queries when you need the data.
The most obvious drawback of LINQ to SQL is the fact that it's limited to SQL server database engine.
In fact LINQ to SQL should be more realistically named LINQ to SQL Server. In the future there will be other LINQ providers for different databases
For the LINQ to SQL, there is a good article written by Scott Guthrie in his blog post and I think
you might refer to his article
Below is the URL
http://weblogs.asp.net/scottgu/archive/2007/05/19/using-linq-to-sql-part-1.aspx
Thats all for the LINQ article that I would like to share
Other Related and Popular Articles :
Author Profile : Sanjay Shravan
How would you rate the quality of this content?
Poor
Excellent
Comments
Leave New Comments
Article Content copyright by
Sanjay Shravan
Everything else Copyright © by
WorldofASP.NET
2008