使用Linq将List <string>转换为List <KeyValuePair <string,string >>

cuo*_*gle 7 c# linq lambda

可能重复:
是否有LINQ方式从键/值对列表转到字典?

假设我有List<string>如下:

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

根据这个列表,我想转换为List<KeyValuePair<string, string>>,原因是允许相同的键,这就是为什么我不使用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"),
                       };
Run Code Online (Sandbox Code Playgroud)

我可以通过使用下面的代码来实现:

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));
Run Code Online (Sandbox Code Playgroud)

但是觉得这不是使用循环的最佳方式for,有没有其他方法可以使用内置的LINQ来实现它?

dtb*_*dtb 9

var output = Enumerable.Range(0, input.Count / 2)
                       .Select(i => Tuple.Create(input[i * 2], input[i * 2 + 1]))
                       .ToList();
Run Code Online (Sandbox Code Playgroud)


O. *_*per 5

我不建议在这里使用LINQ,因为没有理由和你没有通过使用LINQ获得任何东西,而只是使用普通for循环并在每次迭代中将计数变量增加2:

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]));
}
Run Code Online (Sandbox Code Playgroud)

请注意,我正在启动索引,1所以input如果项目的数量是奇数,即如果input以"半对"值结束,则不会遇到访问无效索引的异常.