Starting Basic Queries with LINQ

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

               };

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s