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

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" },
                   };
    }
}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)