How to "change" a record inside a list / array / enumerable?

1.4k views Asked by At

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:

  1. Get a copy of the record with changed value
  2. Find the index of the record in the list
  3. 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.

1

There are 1 answers

2
Ilya Chernomordik On BEST ANSWER

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.