Assigning values inside a LINQ Select?

后端 未结 3 1277
小蘑菇
小蘑菇 2020-12-06 16:36

I have the following query:

drivers.Select(d => { d.id = 0; d.updated = DateTime.Now; return d; }).ToList();

drivers is a List which com

3条回答
  •  孤街浪徒
    2020-12-06 16:54

    Ok I will make an answer myself.

    Xaisoft, Linq queries, be it lambda expression or query expression, shouldn't be used to mutate list. Hence your Select

    drivers = drivers.Select(d => { d.id = 0; d.updated = DateTime.Now; return d; }).ToList();
    

    is bad style. It confuses/unreadable, not standard, and against Linq philosophy. Another poor style of achieving the end result is:

    drivers.Any(d => { d.id = 0; d.updated = DateTime.Now; return false; });
    

    But that's not to say ForEach on List 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 as a terminating call to Linq expression (ie, if the assignment is not meant to be a query but an execution).

提交回复
热议问题