请看下面的代码:
SomeList.Where(x => !x.Name.Equals("NO")).All(x => x.flag=true);
SomeList 是一个 ICollection
对于SomeList中的每一个对象,如果Name不是NO,对象的flag应更新为 true。现在的问题是 flag 是 bool?
我应该如何为这样的 lambda 表达式中的 flag 赋值?
请您参考如下方法:
您实际上是想避免使用 foreach,这是徒劳的。 Alexander 的答案使用 ForEach 扩展方法,但是您还必须使用 ToList 方法实现一个列表。
最优雅的方法是只使用 foreach 循环。
foreach (var item in SomeList.Where(x => !x.Name.Equals("NO")))
item.flag = true;
如果您真的想要一种函数式编程风格来调用集合的所有成员的操作,请编写您自己的扩展方法或使用 Ix.NET which already provides such helper extensions .
var n = 0;
Enumerable.Range(0, 10).Do(x => n += x)
它提供以下重载
IEnumerable<TSource> Do<TSource>(this IEnumerable<TSource> source, Action<TSource> onNext)
IEnumerable<TSource> Do<TSource>(this IEnumerable<TSource> source, Action<TSource> onNext, Action onCompleted)
IEnumerable<TSource> Do<TSource>(this IEnumerable<TSource> source, Action<TSource> onNext, Action<Exception> onError)
IEnumerable<TSource> Do<TSource>(this IEnumerable<TSource> source, Action<TSource> onNext, Action<Exception> onError, Action onCompleted)
IEnumerable<TSource> Do<TSource>(this IEnumerable<TSource> source, IObserver<TSource> observer)
