我有一个Obj的集合,我想通过集合,并在条件为真时设置属性,所以在正常的世界中它将是:
foreach (var o in obj)
{
if (o.SomeProperty == Something)
{
o.SomeOtherProperty = true;
}
}
Run Code Online (Sandbox Code Playgroud)
无论如何,使用Linq,使它成为一条线?
LINQ对于执行副作用并不是那么有用,它主要用于查询.事实上,它延迟执行如此根深蒂固的事实使得它成为执行副作用的不良选择,IMO.
你得到的代码对我来说非常好.如果你确实想使用LINQ,我怀疑你可以提高很多:
foreach (var o in obj.Where(i => i.SomeProperty == Something))
{
o.SomeOtherProperty = true;
}
Run Code Online (Sandbox Code Playgroud)
现在,这并不比你原来的更好(可能更糟).
另一方面,如果您想创建一个新的流式序列,其中包含具有所需特征的原始项目的投影,您可以执行以下操作:
var projection = obj.Where(i => i.SomeProperty == Something)
.Select(i => new Foo(i) { SomeOtherProperty = true });
// assuming your type has a copy-constructor
Run Code Online (Sandbox Code Playgroud)
编辑:如果你不想听取专家的意见(阅读:Eric Lippert),你可以编写自己的扩展方法:
public static void Do<T>(this IEnumerable<T> source, Action<T> action)
{
if (source == null)
throw new ArgumentNullException("source");
if (action == null)
throw new ArgumentNullException("action");
foreach (T item in source)
action(item);
}
Run Code Online (Sandbox Code Playgroud)
这将允许您:
obj.Where(o => o.SomeProperty == Something)
.Do(o => o.SomeOtherProperty = true);
Run Code Online (Sandbox Code Playgroud)