简体   繁体   中英

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

Eg:

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 eg

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM