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

前端 未结 5 679
南方客
南方客 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:34

    Note that the dictionary collection initialization { { key1, value1 }, { key2, value2 } } depends on the Dictionary's Add(TKey, TValue) method. You can't use this syntax with the list because it lacks that method, but you could make a subclass with the method:

    public class KeyValueList : List>
    {
        public void Add(TKey key, TValue value)
        {
            Add(new KeyValuePair(key, value));
        }
    }
    
    public class Program
    {
        public static void Main()
        {
            var list = new KeyValueList
                       {
                           { "key1", "value1" },
                           { "key2", "value2" },
                           { "key3", "value3" },
                       };
        }
    }
    

提交回复
热议问题