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

Viewed 48381

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

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

Since collection initializers (C# 6.0) have not been mentioned here:

Implementation

public static class InitializerExtensions
{
   public static void Add<T1, T2>(this ICollection<KeyValuePair<T1, T2>> target, T1 item1, T2 item2)
   {
       if (target == null)
            throw new ArgumentNullException(nameof(target));

        target.Add(new KeyValuePair<T1, T2>(item1, item2));
    }
}

Usage

var list = new List<KeyValuePair<string, string>> { {"ele1item1", "ele1item2"}, { "ele2item1", "ele2item2" } };

How to make it work

Just include the right using statements in your file so that InitializerExtensions is available (meaning you could call InitializerExtensions.Add explicitly) and the special collection initializer syntax will become available if you are using VS 2015 or higher.

Related