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.
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.
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]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With