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:
- Get a copy of the record with changed value
- Find the index of the record in the list
- Assign the new reference
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.
It looks like
dotnetactually has a number of classes for these that are insideSystem.Collections.Immutable.ImmutableListhas aReplacefunction 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.