Sunday, December 5, 2010

LINQ - Beginners Tutorial-1

What is LINQ?
LINQ stands for Language integrated Query, that allows us to query local object collection or remote data source.

Using LINQ we can query any collection implementing IEnumaerable interface. To use LINQ in code we need to use Sysrtem.Linq namespace.

First Example:
string[] names = { "Ajay", "Vijay", "Karan", "Farhan", "Pooja", "Geeta" };
IEnumerable tp = names.Where(n => n.EndsWith("a"));
foreach (string str in tp)
{
Console.WriteLine(str);
}


Here we have taken a string array in first line of code, fnames that contains 6 names.
In second line of code we write a Linq to get the names ending with "a".

Output:
Pooja
Geeta

Main Points:
1. Linq data has two parts, sequence and elements. Here names is a sequence and array members are elements.
2. Linq doesn't alter the input sequence. So result will always be in the order it was input.
3. Linq always return an IEnumerable result.
4. "n => n.EndsWith("a")" is a lambda expression that filters the result for us.

1 comment: