可能重复:
有没有一种办法LINQ从键/值对到字典的名单去?
假设我有一个List<string>
如下:
var input = new List<string>()
{
"key1",
"value1",
"key2",
"value2",
"key3",
"value3",
"key4",
"value4"
};
根据这份名单,我想转换到List<KeyValuePair<string, string>>
,原因是为了让相同的密钥,这就是为什么我不使用词典。
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"),
};
我可以用下面的代码实现:
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));
但是,感觉这是不使用循环最好的办法for
,有没有什么我们可以使用内置的LINQ实现它的另一种方式?