KingNestor KingNestor - 24 days ago 13
C# Question

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.

Answer

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.

Comments