Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
316 views
in Technique[技术] by (71.8m points)

linq - LINQ相当于IEnumerable的foreach <T>(LINQ equivalent of foreach for IEnumerable<T>)

I'd like to do the equivalent of the following in LINQ, but I can't figure out how:

(我想在LINQ中执行以下操作,但是我不知道如何操作:)

IEnumerable<Item> items = GetItems();
items.ForEach(i => i.DoStuff());

What is the real syntax?

(真正的语法是什么?)

  ask by tags2k translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There is no ForEach extension for IEnumerable ;

(没有IEnumerable ForEach扩展;)

only for List<T> .

(仅用于List<T> 。)

So you could do

(所以你可以做)

items.ToList().ForEach(i => i.DoStuff());

Alternatively, write your own ForEach extension method:

(或者,编写您自己的ForEach扩展方法:)

public static void ForEach<T>(this IEnumerable<T> enumeration, Action<T> action)
{
    foreach(T item in enumeration)
    {
        action(item);
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...