C# 列表lambda 查找然后修改元素

发布于 2024-08-21 05:30:22 字数 360 浏览 3 评论 0原文

我将如何使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

绻影浮沉 2024-08-28 05:30:22

好吧,你可以这样做:

list.FindAll(x => x.Seconds == 0)
    .ForEach(x => x.Seconds = seconds);

不过,就我个人而言,我更喜欢对副作用部分使用显式循环:(

foreach (var x in list.Where(x => x.Seconds == 0))
{
    x.Seconds = seconds;
}

顺便说一句,我假设这是一个引用类型。如果它是一个值类型是它不起作用的各种其他原因。)

编辑:您可能希望查看 Eric Lippert 对此事的看法

Well, you could do:

list.FindAll(x => x.Seconds == 0)
    .ForEach(x => x.Seconds = seconds);

Personally I'd prefer an explicit loop for the side-effecting part though:

foreach (var x in list.Where(x => x.Seconds == 0))
{
    x.Seconds = seconds;
}

(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.

没有你我更好 2024-08-28 05:30:22
list.FindAll(x => x.Seconds == 0)
    .ForEach(x => x.Seconds = seconds);   

我相信上面的内容不能编译。
.ForEach(...) 返回 void,它不能位于 FindAll() 方法的右侧。

list.FindAll(x => x.Seconds == 0)
    .ForEach(x => x.Seconds = seconds);   

I believe that the above does not compile.
.ForEach(...) returns void which can not be on the right-hand side of the FindAll() method.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文