Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 333
Brady Moritz Avatar asked Jan 07 '14 02:01

Brady Moritz


2 Answers

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.

like image 112
Jon Skeet Avatar answered Sep 28 '22 11:09

Jon Skeet


You can use a range that is half the length of the list, and ToDictionary to create the dictionary from items from the list:

Dictionary<string, string> dictionary =
  Enumerable.Range(0, list.Count / 2)
  .ToDictionary(i => list[i * 2], i => list[i * 2 + 1]);
like image 28
Guffa Avatar answered Sep 28 '22 13:09

Guffa