C#:有没有办法使用 lambda 表达式设置集合中对象的属性?
我正在开发一个小项目,我想我可以尝试一些我不知道的东西,这样我就可以学习新的东西。 我有一个消息集合,称为 msgs。我想仅过滤未读的内容,然后将其设置为“已读”。 为此,我使用此 lambda 表达式调用了Where方法,我想我会得到所有未读消息的列表。现在我想将该值设置为“Read”(将“T”分配给 MessageRead 属性)。有没有办法使用 lambda 表达式来做到这一点?
我得到了这段代码,但“All”方法不是我想要的,我只是发现它检查列表中的所有元素是否符合此条件。
msgs.Where(message => message.MessageRead == 'F').All(message => message.MessageRead = 'T');
多谢, 奥斯卡
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. 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. Now I would like to set the value to "Read" (assigning 'T' to the MessageRead property). Is there a way to do that using lambda expressions?
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.
msgs.Where(message => message.MessageRead == 'F').All(message => message.MessageRead = 'T');
Thanks a lot,
Oscar
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您需要的是 ForEach 扩展方法,请参阅此处的讨论: LINQ 相当于 IEnumerable 的 foreach< ;T>
What you are after is a ForEach extension method, see discussions here: LINQ equivalent of foreach for IEnumerable<T>
事实上,如果有这样的方法,它不会比常规的 foreach 语句有任何好处。
Eric Lippert(Microsoft 高级软件设计工程师)对此主题有很好的概述:“foreach”与“ForEach”
In fact if there was such a method, it wouldn't had any benefits over regular foreach statement.
Eric Lippert (senior software design engineer at Microsoft) has a good overview of this topic: “foreach” vs “ForEach”
foreach
语句有什么问题?它完全满足您的需要:What's wrong with the
foreach
statement? It does exactly what you need: