C# 列表lambda 查找然后修改元素
我将如何使用 lambda 对列表执行此操作
List<Foo> list....// create and add a bunch of Foo
int seconds = 100;
list.FindAll(x=>(x.Seconds == 0).Seconds = seconds) // yes I know that wont work...
换句话说,找到 Seconds == 0 的所有 foo 对象并将值更改为我的局部变量...
我不想循环列表...我确信有一种方法可以使用简单的 lambda 方法来做到这一点...
任何帮助都表示赞赏
Oneway
How would I go about doing this with a List using lambda
List<Foo> list....// create and add a bunch of Foo
int seconds = 100;
list.FindAll(x=>(x.Seconds == 0).Seconds = seconds) // yes I know that wont work...
In other words, find all of the foo objects that Seconds == 0 and change the value to my local variable...
I don't want to loop the list...I am sure there is a way to do this with a simple lambda method...
Any help appreciated
Oneway
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
好吧,你可以这样做:
不过,就我个人而言,我更喜欢对副作用部分使用显式循环:(
顺便说一句,我假设这是一个引用类型。如果它是一个值类型是它不起作用的各种其他原因。)
编辑:您可能希望查看 Eric Lippert 对此事的看法。
Well, you could do:
Personally I'd prefer an explicit loop for the side-effecting part though:
(I'm assuming this is a reference type, by the way. If it's a value type there are all kinds of other reasons why it wouldn't work.)
EDIT: You may wish to have a look at Eric Lippert's thoughts on the matter too.
我相信上面的内容不能编译。
.ForEach(...)
返回 void,它不能位于FindAll()
方法的右侧。I believe that the above does not compile.
.ForEach(...)
returns void which can not be on the right-hand side of theFindAll()
method.