LINQ the new way to query How to make basic queries

Hi,

One of the best new things in the new Dot net 3.5 is the LINQ. LNQ stands for Language Integrated Query. With the help of LINQ now we can query nearly anything in a more than efficient manner. It also gives us compile time check to the inline query’s, which reduces the chances of runtime error.

A simple query of the LINQ start with the “from” clause and ends with the select clause. This is quite opposite of what we are used to in the SQL (where we have the select clause first and from clause later). Below is the simple example of a Linq Query.

var t = from c in BlogBLL.Categories

               select c;

Here I am selecting all the categories from the data context BlogBLL. The BlogBLL is a data context that contains the mapping of all the tables. If we want to select only some of the properties from the list then we can define them in the select clause like the one below which only selects the Category ID and category name from the category class

var t = from c in BlogBLL.Categories

               select new

               {

                c.CategoryID,

                c.CategoryName

               };

Now if we want to put some condition of the selection then we can use the where clause to define the condition to filter out the records. Below is an example of the same. Here I am filtering out all the records where the categoryID is less than or equal to 5.

var t = from c in BlogBLL.Categories

                where c.CategoryID  <= 5

               select new

               {

                c.CategoryID,

                c.CategoryName

               };

In Visual Studio Orcas 2008 (Beta 2 now) we also get full intellisense for the query. This makes it very easy to create the queries.

These were very basic example to show how we can start writing LINQ queries in the new Dot net framework. Later on I will try and write a small application that uses LINQ for the data access.

Thanks
Vikram


Share this post   Email it |  digg it! |  reddit! |  bookmark it!

Feedback

Please post your comments:

Name:  
Email (optional): Your email address will not be posted.
URL (optional):
Comments: HTML will be ignored, URLs will be converted to hyperlinks  
Enter the text you see in the box:
 
Copyright © 2006 - 2009 Vikram Lakhotia