Manish Pansiniya's Blog

.NET, C#, Javascript, ASP.NET and lots more…:)

Easy way to understand LINQ

leave a comment »

There are many videos and tutorials on LINQ. And i am adding one more to the list. I am not going deeply in LINQ but just giving basic syntax understanding of LINQ.

Following is the description of LINQ

from [identifier] in 
where [boolean expression]
order by [[expression](ascending/descending)], [optionally repeat]
select [expression]
group [expression] by [expression] into [expression]

These LINQ query returns the IEnumerable collection. Let us go line by line into the same.

First line is similar to declaring variable. Here you are declaring variable for your data collection. But this data collection is filter of your source collection. Let’s take one example

var q = from c in contacts

        where c.State == "WA"

        orderby c.LastName, c.FirstName

        select c;

Now, here c is variable and it is subset or equal to contacts. So whenever you have collection from which you want to make queries, first line would be from <Identifier> in <collection>

From next line everybody use expression (Not facial but technical 🙂 ). This expression must use identifier you have defined in the first line. So in above example, you can see that WHERE and ORDERBY uses c to create expression. c has same members which your source has. Suppose you have contact collection named contacts. And you wrote first line like “from c in contacts” then c contain all the members of contact. Visual studio provide Intellisense using which you can easily create the expression. Where takes boolean expression, while order by take just simple expressions.

Once you have setup the LINQ query, you need to select the collection. It would be simple identifier or may be columns from identifier. One more example for understanding is as follows:

int[] nums = new int[] {0,4,2,6,3,8,3,1};


var result = (from n in nums

              where n < 5

              orderby n

              select n).Distinct();

This is just a very basic understanding on LINQ. But its really vast and if you need to go in bit detail, follow Nice website for LINQ :).


Written by Manish

March 23, 2009 at 2:48 pm

Posted in .NET, .NET 3.0, WPF

Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s

%d bloggers like this: