Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
410 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 Answer

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);
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...