2

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

JSBach
  • 4,679
  • 8
  • 51
  • 98

3 Answers3

6

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

Community
  • 1
  • 1
cbp
  • 25,252
  • 29
  • 125
  • 205
  • That is just great! Thanks for your help! You were so fast that I have to wait 10 minutes to accept your answer, as soon as it is possible, I will mark it! – JSBach Mar 02 '11 at 23:53
5

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”

Lloyd
  • 1,324
  • 7
  • 10
  • Yes, I know. In this case, am not doing because it is better, but because I want to learn it. :) – JSBach Mar 03 '11 at 00:04
0

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';
}
LukeH
  • 263,068
  • 57
  • 365
  • 409
  • 1
    Yes, it does. But the problem is that I already know this one. I want to learn new stuff in order to be able to use them if I need ;) – JSBach Mar 03 '11 at 09:54
  • @Oscar: Fair enough, although part of the learning process is discovering what the appropriate techniques are in different scenarios. The correct answer to "How do I open a beer bottle using my cellphone?" is almost always "Don't use your cellphone; use a bottle opener". – LukeH Mar 03 '11 at 13:50
  • 1
    Hi! That is true, but I think we can learn something when they are not necessarily needed but we have time/opportunity to do so, so in the future, case we need it, we already know. Nodoby know, maybe at some point in time all that is left is a cellphone and a bottle :) – JSBach Mar 03 '11 at 19:29