好的,我会自己回答。
Xaisoft,Linq
查询,无论是 lambda 表达式还是查询表达式,都不应该用于变异列表。因此你的Select
drivers = drivers.Select(d => { d.id = 0; d.updated = DateTime.Now; return d; }).ToList();
是坏风格。它令人困惑/不可读,不标准,并且违背Linq
哲学。实现最终结果的另一种糟糕方式是:
drivers.Any(d => { d.id = 0; d.updated = DateTime.Now; return false; });
But that's not to say ForEach
on List<T>
is inappropriate. It finds uses in cases like yours, but do not mix mutation with Linq
query, thats all. I prefer to write something like:
drivers.ForEach(d => d.updated = DateTime.Now);
Its elegant and understandable. Since it doesn't deal with Linq
, its not confusing too. I don't like that syntax for multiple statements (as in your case) inside the lambda. It's a little less readable and harder to debug when things get complex. In your case I prefer a straight foreach
loop.
foreach (var d in drivers)
{
d.id = 0;
d.updated = DateTime.Now;
}
Personally I like ForEach
on IEnumerable<T>
as a terminating call to Linq
expression (ie, if the assignment is not meant to be a query but an execution).