WorldofASP.NET : ASP.NET Directory, Tutorial, Hosting, and Source Code
You are 1 of 132 users


WorldofASP.NET >> .NET 3.5 >> Unedited .NET 3

Basic introduction of LINQ

This article covers basic introduction of LINQ
Published Date : 10 Aug 2008
Author : Sanjay Shravan
Language : C#
Platform : .NET
Technology : ASP.NET
Views : 1159
Rating : (0 votes so far)



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
         Employees
Black                     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

Tag Cloud
  asp.net random number   asp.net activate user   datalist control   asp.net delegate   feedback form in asp.net   httpwebrequest httpwebresponse   xhtml-mp asp.net   smart device application   create httpwebrequest   httpmodule httphandler   asp.net cookie shopping cart   upload file progress bar asp.net   asp.net listbox control   asp.net url parameters   asp.net httpwebrequest   asp httpwebrequest   asp.net pass data from one page to another   formview displaying inserted data   asp.net tooltip   form view in asp.net   httpwebrequest vb.net   edit update insert in a gridview c#   asp.net upload ajax progress   ajax updatepanel button   encrypt querystring in asp.net   asp.net file upload progress bar   contact us asp.net   httpwebrequest   formview asp.net   asp.net cookies encryption   httpwebrequest create   generate random number asp.net   cannot start service from the command line or a debugger. a windows service must   httpwebrequest .net   tooltip asp.net   httpwebrequest asp.net c#   "javascript in asp.net"   asp.net encryption   httpwebrequest in asp.net 2.0   asp.net file upload progress   frames image gallery thumbnails asp.net   cannot start service from the command line or a debugger   checkboxlist datasource   httpwebresponse





Other Related and Popular Articles :

Implement a simple windows communication foundation
Create the Derivatives Calculator Service which implement WCF

Basic Silverlight programming in VS 2008
This article teach you how to code Silverlight by using Visual Studio 2008

Visions in Online Crystal Ball: Is Silverlight 2.0 THE NEXT BIG THING
General article about Silverlight 2.0

Introduction to Language Integrated Query (LINQ)
Building the Data Access Layers Using LINQ to SQL in ASP.NET 3.5

Enhancing Web Experience with Siverlight
Developing a sample application to integrate silverlight with ASP.NET


Author Profile : Sanjay Shravan

Click here to view Author Profile


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

Category
.NET 3.5
AJAX and ATLAS
ASP.NET
C# Programming
Classic ASP
Enterprise Systems
General .NET
VB.NET Programming
Announcements
Earn Cash by writing an article or review
For more info Click here







Legend : - Within 3 Days - Within 6 Days - Within 9 Days

Home | Add Resources | Sponsored Listings | Advertise with Us | SiteMap 1 | SiteMap 2 | Link To Us | Contact Us
© 2002-2008 Worldofasp.net ASP.NET Directory, Hosting and Tutorials | All rights reserved
Our Partners : ASP.NET Web Hosting | Windows Web Hosting | ASP.NET Hosting | Phone Card | PHP Directory | Bangkok Hotels |Calling Card