What do they mean when they say that LINQ is compositional?

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

+3
source share
2 answers

This means that you can add additional “operators” to the query. This is important because you can do it extremely efficiently.

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

var employees = GetEmployees();

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

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

You can call this function to get managers who are approaching retirement and send them the following email:

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

Pop quiz: How many times will your staff list be repeated? The answer is exactly once; the whole operation is still O (n)!

, . :

var retiringManagers = GetEmployees();
retiringManagers = retiringManagers.Where(e => e.IsManager);
retiringManagers = retiringManagers.Where(m => m.Age >= 65);
foreach (var manager in retiringMangers)
{
    SendPreRetirementMessage();
}

- , , if, , - .

+5

, , , ,

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

Source: https://habr.com/ru/post/1712900/


All Articles