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>>();
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<TKey, TValue> : List<KeyValuePair<TKey, TValue>>
{
public void Add(TKey key, TValue value)
{
Add(new KeyValuePair<TKey, TValue>(key, value));
}
}
public class Program
{
public static void Main()
{
var list = new KeyValueList<string, string>
{
{ "key1", "value1" },
{ "key2", "value2" },
{ "key3", "value3" },
};
}
}
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.