简体   繁体   English

C#:有没有办法使用lambda表达式设置集合中对象的属性?

[英]C#: is there a way to set a property of objects in a collection using lambda expression?

I am developing a small project and I thought I could try something I don't know so I can learn something new. 我正在开发一个小项目,我想我可以尝试一些我不知道的东西,这样我就可以学到新东西。 I have a collection of Messages, called msgs. 我有一组消息,叫做msgs。 I would like to filter only the unread ones and then set it to "read". 我想只过滤未读的,然后将其设置为“读取”。 To do that, I called the Where method with this lambda expression, I imagine I would get a list of all messages which are unread. 为此,我用这个lambda表达式调用了Where方法,我想我会得到一个未读的所有消息的列表。 Now I would like to set the value to "Read" (assigning 'T' to the MessageRead property). 现在我想将值设置为“Read”(将“T”指定给MessageRead属性)。 Is there a way to do that using lambda expressions? 有没有办法使用lambda表达式?

I got to this code, but the "All" method is not what I am loking for, I just found out that it checks if all the elements in the list match this condition. 我得到了这个代码,但是“All”方法不是我所要求的,我只是发现它检查列表中的所有元素是否符合这个条件。

msgs.Where(message => message.MessageRead == 'F').All(message => message.MessageRead = 'T');

Thanks a lot, Oscar 非常感谢,奥斯卡

你所追求的是一个ForEach扩展方法,请参见这里的讨论: LINQ相当于foreach for IEnumerable <T>

In fact if there was such a method, it wouldn't had any benefits over regular foreach statement. 事实上,如果有这样一种方法,它就不会比常规的foreach声明有任何好处。

Eric Lippert (senior software design engineer at Microsoft) has a good overview of this topic: “foreach” vs “ForEach” Eric Lippert(微软高级软件设计工程师)对这个主题有一个很好的概述: “foreach”vs“ForEach”

What's wrong with the foreach statement? foreach声明有什么问题? It does exactly what you need: 它完全符合您的需求:

foreach (var msg in msgs.Where(m => m.MessageRead == 'F'))
{
    msg.MessageRead = 'T';
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM