How do you use object initializers for a list of key value pairs?

前端 未结 5 680
南方客
南方客 2020-12-29 17:46

I can\'t figure out the syntax to do inline collection initialization for:

var a = new List>();
5条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-29 18:32

    Another alternative that doesn't require making a subclass:

    List> list = new Dictionary
        {
            {"key1", "value1"},
            {"key2", "value2"},
        }.ToList();
    

    As mentioned in the comments: drawbacks with this method include possible loss of ordering and inability to add duplicate keys.

提交回复
热议问题