Search code examples
c#key-value

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


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

var a = new List<KeyValuePair<string, string>>();

Solution

  • Pretty straightforward:

    var a = new List<KeyValuePair<string, string>>()
    {
        new KeyValuePair<string, string>("A","B"),
        new KeyValuePair<string, string>("A","B"),
        new KeyValuePair<string, string>("A","B"),
    };
    

    Note that you can leave the trailing comma after the last element (probably because .net creators wanted to make automatic code-generation easier), or remove the () brackets of the list contructor and the code still compiles.