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
你所追求的是一个ForEach扩展方法,请参见这里的讨论: LINQ相当于foreach for IEnumerable <T>
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”
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';
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.