LINQ equivalent of foreach for IEnumerable

2018-12-31 03:15发布

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?

21条回答
零度萤火
2楼-- · 2018-12-31 03:38

You could use the FirstOrDefault() extension, which is available for IEnumerable<T>. By returning false from the predicate, it will be run for each element but will not care that it doesn't actually find a match. This will avoid the ToList() overhead.

IEnumerable<Item> items = GetItems();
items.FirstOrDefault(i => { i.DoStuff(); return false; });
查看更多
不再属于我。
3楼-- · 2018-12-31 03:40

For VB.NET you should use:

listVariable.ForEach(Sub(i) i.Property = "Value")
查看更多
忆尘夕之涩
4楼-- · 2018-12-31 03:42

Many people mentioned it, but I had to write it down. Isn't this most clear/most readable?

IEnumerable<Item> items = GetItems();
foreach (var item in items) item.DoStuff();

Short and simple(st).

查看更多
ら面具成の殇う
5楼-- · 2018-12-31 03:42

MoreLinq has IEnumerable<T>.ForEach and a ton of other useful extensions. It's probably not worth dependency just for ForEach, but there's a lot of useful stuff in there.

https://www.nuget.org/packages/morelinq/

https://github.com/morelinq/MoreLINQ

查看更多
忆尘夕之涩
6楼-- · 2018-12-31 03:43

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);
    }
}
查看更多
残风、尘缘若梦
7楼-- · 2018-12-31 03:44

The purpose of ForEach is to cause side effects. IEnumerable is for lazy enumeration of a set.

This conceptual difference is quite visible when you consider it.

SomeEnumerable.ForEach(item=>DataStore.Synchronize(item));

This wont execute until you do a "count" or a "ToList()" or something on it. It clearly is not what is expressed.

You should use the IEnumerable extensions for setting up chains of iteration, definining content by their respective sources and conditions. Expression Trees are powerful and efficient, but you should learn to appreciate their nature. And not just for programming around them to save a few characters overriding lazy evaluation.

查看更多
登录 后发表回答