Working with LINQ and Lambda expressions

Hi,

Continuing on my post on Lambda and LINQ, in this post I will talk about how to use the lambda expression in the LINQ query. LINQ query can work great without the Lambda expression. But we can also use Lambda expression in the LINQ query.

;

Do check these earlier post of mine on the Lambda expresions and LINQ Query

     C Sharp 3.0 new Features Lambda Expressions
     Starting with the basic of Lambda Expression

     Some examples on how to use Lambda Expression
     Starting Basic Queries with LINQ
     Using LINQ to get the information about all the methods in a type
     Working with LINQ queries and Inner Join


In this post I will use the LINQ query from my previous examples and create the same query using Lambda expression. This will help in understanding how can Lambda expressions be useful in writing the LINQ queries.

Previous LINQ query (Select some fields from a given class using the anonymous types)

 var t = from c in BlogBLL.Categories

               select new

               {

                c.CategoryID,

                c.CategoryName

               };

Its Lambda equivalent would be

var t = BlogBLL.Categories.Select(c => new {c.CategoryID, c.CategoryName});

LINQ query to select some fields from the category class where the categoryId is greater than equal to 5

var t = from c in BlogBLL.Categories

                where c.CategoryID  <= 5

               select new

               {

                c.CategoryID,

                c.CategoryName

               };


Its Lambda equivalent would be

var t = BlogBLL.Categories.Where(c => c.CategoryID <= 5)

        .Select(c => new {c.CategoryID, c.CategoryName});

Hope this makes it easy to understand how much of help Lambda expression can be when writing the LINQ expressions.

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