我想在LINQ中执行以下等效操作,但我无法确定如何执行:
IEnumerable<Item> items = GetItems();
items.ForEach(i => i.DoStuff());
真正的语法是什么?
我想在LINQ中执行以下等效操作,但我无法确定如何执行:
IEnumerable<Item> items = GetItems();
items.ForEach(i => i.DoStuff());
真正的语法是什么?
当前回答
很多人都提到过,但我不得不把它写下来。这不是最清晰/最可读吗?
IEnumerable<Item> items = GetItems();
foreach (var item in items) item.DoStuff();
简短而简单(st)。
其他回答
微软发布了一个LINQ交互扩展的实验版本(也在NuGet上,更多链接请参见RxTeams的简介)。9频道的视频很好地解释了这一点。
它的文档仅以XML格式提供。我在Sandcastle中运行了这个文档,以使其具有更可读的格式。解压缩文档存档并查找index.html。
在许多其他好处中,它提供了预期的ForEach实现。它允许您编写如下代码:
int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8 };
numbers.ForEach(x => Console.WriteLine(x*x));
如果您想充当枚举滚动,则应生成每个项。
public static class EnumerableExtensions
{
public static IEnumerable<T> ForEach<T>(this IEnumerable<T> enumeration, Action<T> action)
{
foreach (var item in enumeration)
{
action(item);
yield return item;
}
}
}
ForEach的目的是造成副作用。IEnumerable用于集合的惰性枚举。
当你考虑到这一点时,这个概念上的差异是非常明显的。
SomeEnumerable.ForEach(item=>DataStore.Synchronize(item));
在您对其执行“计数”或“ToList()”或其他操作之前,这不会执行。这显然不是所表达的。
您应该使用IEnumerable扩展来设置迭代链,根据其各自的源和条件定义内容。表达树是强大而高效的,但你应该学会欣赏它们的本质。而且不仅仅是为了围绕它们进行编程,以节省几个字符而忽略惰性求值。
ForEach也可以链接,只需在动作后放回桩线即可。保持流利
Employees.ForEach(e=>e.Act_A)
.ForEach(e=>e.Act_B)
.ForEach(e=>e.Act_C);
Orders //just for demo
.ForEach(o=> o.EmailBuyer() )
.ForEach(o=> o.ProcessBilling() )
.ForEach(o=> o.ProcessShipping());
//conditional
Employees
.ForEach(e=> { if(e.Salary<1000) e.Raise(0.10);})
.ForEach(e=> { if(e.Age >70 ) e.Retire();});
实现的一个版本。
public static IEnumerable<T> ForEach<T>(this IEnumerable<T> enu, Action<T> action)
{
foreach (T item in enu) action(item);
return enu; // make action Chainable/Fluent
}
编辑:Lazy版本使用的是收益率返回,如下所示。
public static IEnumerable<T> ForEachLazy<T>(this IEnumerable<T> enu, Action<T> action)
{
foreach (var item in enu)
{
action(item);
yield return item;
}
}
Lazy版本需要具体化,例如ToList(),否则什么都不会发生。请参阅以下ToolmakerSteve的精彩评论。
IQueryable<Product> query = Products.Where(...);
query.ForEachLazy(t => t.Price = t.Price + 1.00)
.ToList(); //without this line, below SubmitChanges() does nothing.
SubmitChanges();
我将ForEach()和ForEachLazy()都保存在库中。
MoreLinq有IEnumerable<T>.ForEach和许多其他有用的扩展。仅为ForEach使用依赖关系可能不值得,但其中有很多有用的东西。
https://www.nuget.org/packages/morelinq/
https://github.com/morelinq/MoreLINQ