sgowd
sgowd

Reputation: 1034

Easiest way to update items in a c# list

I want to update a c# boolean list that is already existing.

Does below work?

myList.ForEach(item => item = true);

why do I see a context warning that

The value passed to the method is never used because it is overwritten in the method body before being read

Upvotes: 2

Views: 146

Answers (1)

siride
siride

Reputation: 209465

What you have as item is actually just a parameter for a lambda function. If you assign it, you are only modifying the parameter, not the value in the list. It's a valid thing to do, but it's not usually sensible, thus the warning.

If you want to actually update the values in the list, you need to do something like:

for(var i = 0; i < myList.Length; i++)
    myList[i] = true;

Looks more verbose? It is. But iterators aren't designed for mutation. If you are okay with generating a new list and replacing myList entirely, then you can just do:

myList = myList.Select(item => true).ToList();

Note that the original list will be gone.

Upvotes: 3

Related Questions