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
ImmutableDictionary<string, string> collection1 = ImmutableDictionary
.Create<string, string>(StringComparer.InvariantCultureIgnoreCase)
.AddRange(
new[]
{
new KeyValuePair<string, string>("a", "a"),
new KeyValuePair<string, string>("b", "b"),
});
We have created an empty collection then created another one with some values.
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();
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
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();
This is short form of the previous case (Create + ToBuilder)
CreateRange
ImmutableDictionary<string, string> collection4 = ImmutableDictionary
.CreateRange(new[]
{
new KeyValuePair<string, string>("a", "a"),
new KeyValuePair<string, string>("b", "b"),
});
This is short form of the first case (Create + AddRange)
ToImmutableDictionary
ImmutableDictionary<string, string> collection5 = new Dictionary<string, string>
{
{ "a", "a" },
{ "b", "b" }
}.ToImmutableDictionary();
Last but not least here we have used a converter.