jsc*_*rle 4 .net c# immutable-collections c#-8.0 .net-5
我似乎无法弄清楚如何将项目添加ImmutableList到ImmutableDictionary.
我有以下变量:
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没有设置器。如何在不重建整个词典的情况下替换词典中的列表?
ImmutableCollections 提供了多种构建它们的不同方法。
一般指导是首先填充它们,然后使它们不可变。
Create+AddRangeImmutableDictionary<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+BuilderImmutableDictionary<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)
我们创建了一个空集合,然后将其转换为构建器。
我们已经在其中填充了值。
最后我们构建了不可变集合。
CreateBuilderImmutableDictionary<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)
CreateRangeImmutableDictionary<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)的简写形式
ToImmutableDictionaryImmutableDictionary<string, string> collection5 = new Dictionary<string, string>
{
{ "a", "a" },
{ "b", "b" }
}.ToImmutableDictionary();
Run Code Online (Sandbox Code Playgroud)
最后但并非最不重要的一点是,我们在这里使用了转换器。
| 归档时间: |
|
| 查看次数: |
1093 次 |
| 最近记录: |