How can I create a new instance of ImmutableDictionary?

前端 未结 5 1802
慢半拍i
慢半拍i 2020-12-15 15:18

I would like to write something like this:

var d = new ImmutableDictionary { { \"a\", 1 }, { \"b\", 2 } };

(using

5条回答
  •  执笔经年
    2020-12-15 15:37

    Either create a "normal" dictionary first and call ToImmutableDictionary (as per your own answer), or use ImmutableDictionary<,>.Builder:

    var builder = ImmutableDictionary.CreateBuilder();
    builder.Add("a", 1);
    builder.Add("b", 2);
    var result = builder.ToImmutable();
    

    It's a shame that the builder doesn't have a public constructor as far as I can tell, as it prevents you from using the collection initializer syntax, unless I've missed something... the fact that the Add method returns void means you can't even chain calls to it, making it more annoying - as far as I can see, you basically can't use a builder to create an immutable dictionary in a single expression, which is very frustrating :(

提交回复
热议问题