LINQ的风格和QUOT;对于每个"风格、LINQ、QUOT

2023-09-02 21:56:31 作者:初遇ら

可能重复:   的LINQ的foreach的IEnumerable的相当于

Possible Duplicate: Linq equivalent of foreach for IEnumerable

是否有任何LINQ风格的语法对于每一个操作?

Is there any linq style syntax for "For each" operations?

有关例如,基于一个集合到另一个,已经存在的添加值:

For instance, add values based on one collection to another, already existing one:

IEnumerable<int> someValues = new List<int>() { 1, 2, 3 };
IList<int> list = new List<int>();

someValues.ForEach(x => list.Add((x + 1));

相反


推荐答案

使用了ToList()扩展方法是最好的选择:

Using the ToList() extension method is your best option:

someValues.ToList().ForEach(x => list.Add(x + 1));

有一个在直接实现的ForEach首创置业没有扩展方法。

There is no extension method in the BCL that implements ForEach directly.

虽然有中没有扩展方法的首创置业的做这个,还有的是的在系统仍然是一种选择命名空间......如果添加无扩展到项目:

Although there's no extension method in the BCL that does this, there is still an option in the System namespace... if you add Reactive Extensions to your project:

using System.Reactive.Linq;

someValues.ToObservable().Subscribe(x => list.Add(x + 1));

这具有相同的最终结果与上述使用了ToList ,反而是(理论上)更有效,因为它直接流值的委托。

This has the same end result as the above use of ToList, but is (in theory) more efficient, because it streams the values directly to the delegate.