Thursday, November 19, 2009

Linq: How to wrap your head around it

LINQ stands for Language INtegrated Query, it was developed with the idea that programers can query data-sources in an object orientated manner. Linq will alow you to query any IEnumerable source and is available from the .Net 3 framework.

A typical Linq statement looks something like this:

var result = from customer in customers
where customer.Items.Count > 0
select customer;

in this example the result variable will be filled with customers that bought items at our shop.

To understand LINQ, you need to understand the parts that makes it work.

THE FROM CLAUSE:
the first part of LINQ looks something like this:
from customer in customers

This is were you spesify the range variable, it works in a simmilar maner as a foreach loop:
foreach(customer in customers)

The compiler is smart enough to interpret the data types and will return a collection of customers.

THE WHERE CLAUSE:
The were clause is also known as a filter and looks something like this:
where customer.Items.Count > 0

The filter can be any Boolean expression and because you are working with typed objects you are allowed to call on properties. (Whoop for OOP)
You are even allowed to build nested queries if you would like to.

THE SELECT CLAUSE:
The select clause is also known as projection. This is the statement that determines what is being returned. It looks something like this:
select customer;

the select clause can return any result even newly constructed classes for example:
select new EmailDetail {Name = customer.Name, Email = customer.Email)

in this case the compiler will interpret the type of object to return, and the result variable will be a list of email addresses.

EYE OPENING MOMENT:
The most important thing about understanding LINQ is that it is used in a programing environment. There is a big similarity between a SQL statement and a LINQ statement but the key difference is that the from clause begins the LINQ query and the select clause ends it. The from statement must be first because .Net requires that variables must be declared before they are used.

Hope this helps in understanding.
Eduard Kruger

1 comment: