简体   繁体   English

如何“更改”列表/数组/可枚举中的记录?

[英]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.这当然意味着创建 object 的副本,更改该值,然后引用新记录而不是列表中的旧记录。

I am wondering if there is some smart and neat way of doing it in C#.我想知道在 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或者,如果它不是列表而是 Enumerable,则删除一个项目并放置一个新项目,例如

It looks like dotnet actually has a number of classes for these that are inside System.Collections.Immutable .看起来dotnet实际上在System.Collections.Immutable中有许多类。

ImmutableList has a Replace function that will do exactly what I need. ImmutableList有一个Replace function 可以满足我的需要。

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.它也将返回一个新列表,因为列表本身是不可变的,因此如果不希望这样做,则必须实现一个大致相同的扩展方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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