Regardless of whether the type of c
is a reference type or a value type, when setting a variable c = something
, you are overwriting whatever the variable referred to. So the original object that c
referred to is no longer referenced. This does not change the list from updating its reference either though, that’s simply not how it works.
If you want to replace some elements in your list by something else, you will need to use Select
:
list.Select(c =>
{
if (SomeCondition)
return new SomeClass();
// default case, return the same element
return c;
}.ToList();
Note that this creates a new list, so the old list still contains the same elements.
If you wanted to actually replace elements in the original list, you will have to overwrite the elements in the list by accessing its index. You can do this with a normal for
loop:
for (int i = 0; i < list.Count; i++)
{
if (SomeCondition)
{
list[i] = new SomeClass();
}
}
This will actually mutate the existing list and replace some elements inside of it.
1
solved ForEach List