Convert List<string> to List<KeyValuePair<string, string>> using Linq

Viewed 21139

Possible Duplicate:
Is there a LINQ way to go from a list of key/value pairs to a dictionary?

Assume that I have a List<string> as below:

var input = new List<string>()
                       {
                           "key1",
                           "value1",
                           "key2",
                           "value2",
                           "key3",
                           "value3",
                           "key4",
                           "value4"
                       };

Based on this list, I would like to convert to List<KeyValuePair<string, string>>, the reason is to allow the same key, that's why I don't use Dictionary.

var output = new List<KeyValuePair<string, string>>()
                       {
                           new KeyValuePair<string, string>("key1", "value1"),
                           new KeyValuePair<string, string>("key2", "value2"),
                           new KeyValuePair<string, string>("key3", "value3"),
                           new KeyValuePair<string, string>("key4", "value4"),
                       };

I can achieve by using below code:

var keys = new List<string>();
var values = new List<string>();

for (int index = 0; index < input.Count; index++)
{
    if (index % 2 == 0) keys.Add(input[index]);
    else values.Add(input[index]);
}

var result = keys.Zip(values, (key, value) => 
                        new KeyValuePair<string, string>(key, value));

But feeling that this is not the best way using loop for, is there any another way that we can use built-in LINQ to achieve it?

4 Answers
Related