Friday, July 03, 2009

LINQ Example

LINQ (Language Integrated Query) is Microsoft query language that enable you to not just query your objects collection directly (List), but also XML documents, DataRow from relational database system.

Characteristics:
- Only works with supportable data source (backed by LINQ provider). LINQ to Objects|SQL|XML|Entities|DataSets.
- Deferred execution.


Imagine the following scenarios:

1. How do you select a customers with country='gb'?

var customers = new List{
new Customer(){ID=1, Name="Abba", Country="gb", Yob="1950"},
new Customer(){ID=2, Name="Bubble", Country="gb", Yob="1970"},
new Customer(){ID=3, Name="Chaplin", Country="us", Yob="1940"},
new Customer(){ID=4, Name="Gum", Country="gb", Yob="2009"},
};

Normal way:
foreach(Customer c in customers)
{
if(c.country.ToLover().Equals("gb") {...}
}

LINQ way:

var query = from c in customers
where c.country.ToLower().Equals("gb")
select c;

Verdict:
Nothing special. right?

2. What if you want to sort the results of scenario 1 by name (ASC) followed by year of birth (DESC)?

LINQ:
var query = from c in customers
where c.country.Equals("gb")
orderby c.name ascending, c.yob descending,
select c;

3. Any shortcut to scenario 2. Yes.
The LINQ query could further translate to
var query =
customers.OrderBy(s=> s.name).OrderByDescending(s=>s.yob);

4. How to find distinct word from senteces?
string[] chickenQuotes = {
"
The chicken did not cross the road. This is a complete fabrication. We do not even have a chicken",
"
We just want to know if the chicken is on our side of the road or not. The chicken is either with us or against us."
}

var query =
(from
chickenQuotes.SelectMany(s=>s.Split(' '))
where !word.Equals('.')
select word).Distinct();


Home time.. continue later