快速提问,请看这段代码:
List<int> result = new List<int>();
var list = new List<int> { 1, 2, 3, 4 };
list.Select(value =>
{
result.Add(value);//Does not work??
return value;
});
和:
result.Count == 0 //true
为什么 result.Add(value) 没有执行?
但是这没有执行,另一个问题是有办法在 IEnumerable 上用 Extension Method 做一个 foreach 吗?
除了这种方式:IEnumerable.ToList().Foreach(p=>...)
最佳答案
Why result.Add(value) not executed?
这是因为 LINQ 使用延迟执行。在您实际枚举结果(Select
的返回)之前,委托(delegate)不会执行。
为了演示,请尝试以下操作:
List<int> result = new List<int>();
var list = new List<int> { 1, 2, 3, 4 };
var results = list.Select(value =>
{
result.Add(value);//Does not work??
return value;
});
foreach(var item in results)
{
// Just iterating through this will cause the above to execute...
}
话虽如此,这是一个坏主意。如果可以避免,LINQ 查询不应有副作用。将 Select
视为一种转换数据的方式,而不是执行代码的方式。
However this not executed, Another question that is have a way do a foreach on a IEnumerable with Extention Method?
您可以编写自己的扩展方法:
public static void ForEach<T>(this IEnumerable<T> items, Action<T> action)
{
foreach(var item in items)
action(item);
}
但是,我建议不要这样做。详见Eric Lippert's post on the subject .
关于c# - 在 IEnumerable 上使用扩展方法的 Foreach,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8437980/