将项目添加到 ImmutableDictionary<TKey, TValue> 内的 ImmutableList<T>

jsc*_*rle 4 .net c# immutable-collections c#-8.0 .net-5

我似乎无法弄清楚如何将项目添加ImmutableListImmutableDictionary.

我有以下变量:

ImmutableDictionary<string, ImmutableList<string>> _attributes = ImmutableDictionary<string, ImmutableList<string>>.Empty;
Run Code Online (Sandbox Code Playgroud)

我试图在列表中添加一个值:

string[] attribute = line.Split(':');
if (!_attributes.ContainsKey(attribute[0]))
    _attributes = _attributes.Add(attribute[0], ImmutableList<string>.Empty);
if (attribute.Length == 2)
    _attributes[attribute[0]] = _attributes[attribute[0]].Add(attribute[1]);
Run Code Online (Sandbox Code Playgroud)

但是,我收到一条错误消息,指出ImmutableList没有设置器。如何在不重建整个词典的情况下替换词典中的列表?

Pet*_*ala 6

ImmutableCollections 提供了多种构建它们的不同方法。
一般指导是首先填充它们,然后使它们不可变。

Create+AddRange

ImmutableDictionary<string, string> collection1 = ImmutableDictionary
    .Create<string, string>(StringComparer.InvariantCultureIgnoreCase)
    .AddRange(
        new[]
        {
            new KeyValuePair<string, string>("a", "a"),
            new KeyValuePair<string, string>("b", "b"),
        });
Run Code Online (Sandbox Code Playgroud)

我们创建了一个空集合,然后创建了另一个包含一些值的集合。

Create+Builder

ImmutableDictionary<string, string>.Builder builder2 = ImmutableDictionary
    .Create<string, string>(StringComparer.InvariantCultureIgnoreCase)
    .ToBuilder();

builder2.AddRange(
    new[]
    {
        new KeyValuePair<string, string>("a", "a"),
        new KeyValuePair<string, string>("b", "b"),
    });

ImmutableDictionary<string, string> collection2 = builder2.ToImmutable();
Run Code Online (Sandbox Code Playgroud)

我们创建了一个空集合,然后将其转换为构建器。
我们已经在其中填充了值。
最后我们构建了不可变集合。

CreateBuilder

ImmutableDictionary<string, string>.Builder builder3 = ImmutableDictionary
    .CreateBuilder<string, string>(StringComparer.InvariantCultureIgnoreCase);

builder3
    .AddRange(
        new[]
        {
            new KeyValuePair<string, string>("a", "a"),
            new KeyValuePair<string, string>("b", "b"),
        });

ImmutableDictionary<string, string> collection3 = builder3.ToImmutable();
Run Code Online (Sandbox Code Playgroud)

这是前一个案例的简写形式 ( Create+ ToBuilder)

CreateRange

ImmutableDictionary<string, string> collection4 = ImmutableDictionary
    .CreateRange(new[]
    {
        new KeyValuePair<string, string>("a", "a"),
        new KeyValuePair<string, string>("b", "b"),
    });
Run Code Online (Sandbox Code Playgroud)

这是第一种情况 ( Create+ AddRange)的简写形式

ToImmutableDictionary

ImmutableDictionary<string, string> collection5 = new Dictionary<string, string>
{
    { "a", "a" },
    { "b", "b" }
}.ToImmutableDictionary();
Run Code Online (Sandbox Code Playgroud)

最后但并非最不重要的一点是,我们在这里使用了转换器。