在LINQ Select中分配值? [英] Assigning values inside a LINQ Select?

查看:71
本文介绍了在LINQ Select中分配值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下查询:

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

drivers是一个列表,其中带有不同的ID和更新的值,因此我在Select中更改了值,但这是执行此操作的正确方法.我已经知道我不会将驾驶员重新分配给驾驶员,因为Resharper对此有所抱怨,所以我想如果这样的话会更好:

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

但是这仍然是人们应该为驱动程序列表中的每个元素分配新值的方式吗?

解决方案

尽管这看起来很纯洁,尤其是结合了立即执行代码的ToList调用,但我绝对不会在查询中修改任何内容:技巧很不寻常,以至于会使您的程序读者,甚至是经验丰富的读者都感到震惊,尤其是如果他们从未见过.

foreach循环没有任何问题-您可以使用LINQ进行 操作,但这并不意味着您应该进行操作.

I have the following query:

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

drivers is a List which comes in with different id's and updated values, so I am changing the values in the Select, but is the proper way to do it. I already know that I am not reassigning drivers to drivers because Resharper complains about it, so I guess it would be better if it was:

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

but is this still the way someone should assign new values to each element in the drivers List?

解决方案

Although this looks innocent, especially in combination with a ToList call that executes the code immediately, I would definitely stay away from modifying anything as part of a query: the trick is so unusual that it would trip up readers of your program, even experienced ones, especially if they never saw this before.

There's nothing wrong with foreach loops - the fact that you can do it with LINQ does not mean that you should be doing it.

这篇关于在LINQ Select中分配值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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