I can't seem to figure out how add items to an ImmutableList
inside of an ImmutableDictionary
.
I have the following variable:
ImmutableDictionary<string, ImmutableList<string>> _attributes = ImmutableDictionary<string, ImmutableList<string>>.Empty;
To which I'm trying to add a value inside of the list:
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]);
However, I get an error saying that the ImmutableList
doesn't have a setter. How do I replace the list in the dictionary without having to rebuilt the entire Dictionary?
The ImmutableCollections provide a bunch of different ways how you can construct them.
The general guidance is first populate them then make them immutable.
Create
+AddRange
We have created an empty collection then created another one with some values.
Create
+Builder
We have created an empty collection then converted it to a builder.
We have populated it with values.
Finally we have constructed the immutable collection.
CreateBuilder
This is short form of the previous case (
Create
+ToBuilder
)CreateRange
This is short form of the first case (
Create
+AddRange
)ToImmutableDictionary
Last but not least here we have used a converter.