5

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.

2
  • What do you want to happen when a key is null or two keys are equal or the list has an odd length? Handling these issues will shape the code. Commented Jan 7, 2014 at 3:43
  • in my case, it expects non-null and unique keys. Since I wouldn't try to use those as keys normally, and this is just a shorthand method Commented Jan 13, 2014 at 0:29

4 Answers 4

10

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.

Sign up to request clarification or add additional context in comments.

3 Comments

+1 for daring to favor an old-school longhand method over cute, but less readable, code.
dictionary.Add(...) instead of dictionary[...] = ... has the advantage of throwing an appropriate exception when keys are duplicated.
@TomBlodget: True. Will add a note.
3

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]);

Comments

2

LINQ and GroupBy version:

var dict = source.Select((s, i) => new { s, i })
                 .GroupBy(x => x.i / 2)
                 .ToDictionary(g => g.First().s, g => g.Last().s);

Comments

1

If you need LINQ - you can Zip list to itself first:

var result = list.Where((item, id) => id % 2 == 0)
     .Zip (list.Where((item, id) => id % 2 == 1), 
          (key, value) => new KeyValuePair<string,string>(key, value))
     .ToDictionary(p => p.Key, p => p.Value);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.