Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert List<string> to List<KeyValuePair<string, string>> using Linq [duplicate]

Tags:

c#

lambda

linq

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?

like image 904
cuongle Avatar asked Aug 16 '12 06:08

cuongle


Video Answer


2 Answers

var output = Enumerable.Range(0, input.Count / 2)
                       .Select(i => Tuple.Create(input[i * 2], input[i * 2 + 1]))
                       .ToList();
like image 107
dtb Avatar answered Sep 23 '22 01:09

dtb


I wouldn't suggest using LINQ here as there is really no reason to and you don't gain anything by using LINQ, but simply using a normal for loop and increasing your counting variable by two in each iteration:

var result = new List<KeyValuePair<string, string>>();

for (int index = 1; index < input.Count; index += 2)
{
    result.Add(new KeyValuePair<string, string>(input[index - 1], input[index]));
}

Note that I'm starting my index with 1 so I don't run into an exception for accessing an invalid index in case the number of items in input is odd, i.e. if input ends with a "half pair" of values.

like image 33
O. R. Mapper Avatar answered Sep 19 '22 01:09

O. R. Mapper