当他们说LINQ是可组合的时,它们意味着什么? [英] What do they mean when they say LINQ is composable?
问题描述
这是什么意思,为什么(如果有的话)那么重要?
What does it mean and why (if at all) is it important?
推荐答案
这意味着您可以在查询中添加其他运算符".这很重要,因为您可以非常高效地做到这一点.
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测验:对您的员工列表进行几次迭代?答案是恰好一次;整个操作仍然只是O(n)!
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)!
此外,我不需要为此使用单独的方法.我可以将所有这些步骤组成一个查询:
Also, I don't need to have separate methods for this. I could compose a query with these steps all in one place:
var retiringManagers = GetEmployees();
retiringManagers = retiringManagers.Where(e => e.IsManager);
retiringManagers = retiringManagers.Where(m => m.Age >= 65);
foreach (var manager in retiringMangers)
{
SendPreRetirementMessage();
}
关于此的一个很酷的事情是,我可以在运行时进行更改,这样我就可以在if
块中包含或不包含一部分成分,从而可以在使用时确定使用特定过滤器的决定.运行时,一切仍然变得漂亮.
One cool thing about this is that I can change is at run time, such that I can include or not include one part of the composition inside an if
block, such that the decision to use a specific filter is made at run time, and everything still comes out nice and pretty.
这篇关于当他们说LINQ是可组合的时,它们意味着什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!