Reputation: 30335
I have a list of records that are immutable and I need to "change" a value in one of the records. It will of course mean creating a copy of the object with that value changed and then referencing the new records instead of the old one in the list.
I am wondering if there is some smart and neat way of doing it in C#. So far I have thought only of a straightforward way:
E.g:
var newRecord = oldRecord with { Field = newValue};
var index = list.IndexOf(oldRecord);
list[index] = newRecord;
Alternatively removing an item and putting a new one if it's not a list but an Enumerable e.g.
Upvotes: 2
Views: 1995
Reputation: 30335
It looks like dotnet
actually has a number of classes for these that are inside System.Collections.Immutable
.
ImmutableList
has a Replace
function that will do exactly what I need.
It will return a new list as well, since it's the list itself that is immutable, so if that is not desired one must just implement an extension method that does about the same.
Upvotes: 2