LINQ的风格和QUOT;对于每个" [英] Linq style "For Each"

查看:139
本文介绍了LINQ的风格和QUOT;对于每个"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
  的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.

这篇关于LINQ的风格和QUOT;对于每个&QUOT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆