Initialize Dictionary<string,string> from List<string>

Easiest way to do this, perhaps from an extension method? :

var MyDic = new Dictionary<string,string>{ "key1", "val1", "key2", "val2", ...}; 

Where the dictionary winds up with entries contain key and value pairs from the simple list of strings, alternating every other string being the key and values.

Jon Skeet
people
quotationmark

The alternation is a bit of a pain. Personally I'd just do it longhand:

var dictionary = new Dictionary<string, string>();
for (int index = 0; index < list.Count; index += 2)
{
    dictionary[list[index]] = list[index + 1];
}

You definitely can do it with LINQ, but it would be more complicated - I love using LINQ when it makes things simpler, but sometimes it's just not a great fit.

(Obviously you can wrap that up into an extension method.)

Note that you can use dictionary.Add(list[index], list[index + 1]) to throw an exception if there are duplicate keys - the above code will silently use the last occurrence of a particular key.

people

See more on this question at Stackoverflow