tags:

views:

112

answers:

3

What does it mean and why (if at all) is it important?

+3  A: 

I think it means that you can daisy chain your queries, like this

var peterJacksonsTotalBoxOffice
    = movies.Where(movie => movie.Director == "Peter Jackson")
        .Sum(movie => movie.BoxOffice);
Jan Aagaard
+4  A: 

It means you can add additional "operators" to a query. It's important because you can do it extremely efficiently.

For example, let's say you have a method that returns a list (enumerable) of employees:

var employees = GetEmployees();

and another method that uses that one to return all managers:

IEnumerable<Employee> GetManagers()
{
    return GetEmployees().Where(e => e.IsManager);
}

You can call that function to get managers that are approaching retirement and send them an email like this:

foreach (var manager in GetManagers().Where(m => m.Age >= 65) )
{
   SendPreRetirementMessage(manager);
}

Pop quiz: How many times will that iterate over your employees list? The answer is exactly once; the entire operation is still just O(n)!

Joel Coehoorn
Nice explanation, +1
Meta-Knight
The exactly once part is the payoff of the composability then, eh?
Larsenal
Part of it. The rest is that you can take a method like "GetEmployees()" or "GetManagers()" and use it in an efficient way as a building block to build (compose) new, more complicated queries. Without linq, you'd have to start from scratch with your employees list for each method.
Joel Coehoorn
A: 

I think a linq query can be composed within another

see this question

Surya