IEnumerable< T>的LINQ相当于foreach。 [英] LINQ equivalent of foreach for IEnumerable<T>
本文介绍了IEnumerable< T>的LINQ相当于foreach。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在LINQ中做相同的事情,但我不知道如何:
IEnumerable的<项目> items = GetItems();
items.ForEach(i => i.DoStuff());
真正的语法是什么?
IEnumerable ;没有ForEach扩展。只适用于
$ b $ pre $ lt; code> items.ToList()。ForEach(i => i.DoStuff());
列表< T>
。所以你可以这样做:$ b $ pre $ lt; code> items.ToList()。ForEach(i => i.DoStuff());
或者,编写自己的ForEach扩展方法:
(这个IEnumerable< T>枚举,Action< T>动作)
{
foreach(枚举中的T项)
{
action(item);
}
}
I'd like to do the equivalent of the following in LINQ, but I can't figure out how:
IEnumerable<Item> items = GetItems();
items.ForEach(i => i.DoStuff());
What is the real syntax?
解决方案
There is no ForEach extension for IEnumerable
; only for List<T>
. So you could do
items.ToList().ForEach(i => i.DoStuff());
Alternatively, write your own ForEach extension method:
public static void ForEach<T>(this IEnumerable<T> enumeration, Action<T> action)
{
foreach(T item in enumeration)
{
action(item);
}
}
这篇关于IEnumerable< T>的LINQ相当于foreach。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文