Monday, December 6, 2010

LINQ - Beginners Tutorial-2

Here we will start using some advance operators and will write code as lambda expressions as well as comprehension query.

Input:
string[] names = { "Ajay", "Vijay", "Karan", "Farhan", "Pooja", "Geeta", "Dia" };

Lambda Expression:
IEnumerable tp = names.Where(n => n.EndsWith("a"))
                            .OrderBy(n=> n.Length)
                            .Select(n => n.ToUpper());


Comprenesion Query:
IEnumerable tp = from n in names
                         where n.EndsWith("a")
                         orderby n.Length
                         select n.ToUpper();  
 

Enumerate result:
foreach (string str in tp)
{
     Console.WriteLine(str);
}


Output:
DIA
POOJA
GEETA

Main Points:
1. We have option to use either lambda expressions or comprehension query to get the desired result.
2. Compiler converts comprehension query to lambda expression.

2 comments:

  1. very good article for beginners. Please post the complete linq tutorial. Plz also notify me :bthshariff@gmail.com

    ReplyDelete