Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I iterate over a collection and change values with LINQ extension methods?

Lets say I have a collection of Messages which has the properties "UserID" (int) and "Unread" (bool).

How can I use LINQ extension methods to set Unread = false, for any Message in the collection in whose UserID = 5?

So, I know I can do something like:

messages.Any(m => m.UserID == 5);

But, how do I set the Unread property of each of those with an extension method as well?

Note: I know I should not do this in production code. I'm simply trying to learn some more LINQ-fu.

like image 797
KingNestor Avatar asked Dec 30 '09 16:12

KingNestor


3 Answers

Actually, this is possible using only the built-in LINQ extension methods without ToList.
I believe that this will perform very similarly to a regular for loop. (I haven't checked)

Don't you dare do this in real code.

messages.Where(m => m.UserID == 5)
        .Aggregate(0, (m, r) => { m.Unread = false; return r + 1; });

As an added bonus, this will return the number of users that it modified.

like image 195
SLaks Avatar answered Nov 07 '22 16:11

SLaks


messages.Where(m => m.UserID == 5).ToList().ForEach(m => m.Unread = false);

Then submit the changes.

like image 38
David Avatar answered Nov 07 '22 15:11

David


Standard LINQ extension methods doesn't include side effects aimed methods. However you can either implement it yourself or use from Reactive Extensions for .NET (Rx) like this:

messages.Where(m => m.UserID == 5).Run(m => m.Unread = false);
like image 4
Dzmitry Huba Avatar answered Nov 07 '22 15:11

Dzmitry Huba