Ilya Chernomordik
Ilya Chernomordik

Reputation: 30335

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

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.

Upvotes: 2

Views: 1995

Answers (1)

Ilya Chernomordik
Ilya Chernomordik

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

Related Questions