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

发布于 2024-10-20 07:28:55 字数 399 浏览 2 评论 0原文

我正在开发一个小项目,我想我可以尝试一些我不知道的东西,这样我就可以学习新的东西。 我有一个消息集合,称为 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 技术交流群。

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

发布评论

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

评论(3

软甜啾 2024-10-27 07:28:55

您需要的是 ForEach 扩展方法,请参阅此处的讨论: LINQ 相当于 IEnumerable 的 foreach< ;T>

What you are after is a ForEach extension method, see discussions here: LINQ equivalent of foreach for IEnumerable<T>

马蹄踏│碎落叶 2024-10-27 07:28:55

事实上,如果有这样的方法,它不会比常规的 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”

芯好空 2024-10-27 07:28:55

foreach 语句有什么问题?它完全满足您的需要:

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

What's wrong with the foreach statement? It does exactly what you need:

foreach (var msg in msgs.Where(m => m.MessageRead == 'F'))
{
    msg.MessageRead = 'T';
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文