可能重复:
是否有 LINQ 方法可以从键/值对列表到字典?
假设我有一个List<string>
如下:
var input = new List<string>()
{
"key1",
"value1",
"key2",
"value2",
"key3",
"value3",
"key4",
"value4"
};
基于此列表,我想转换为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"),
};
我可以通过使用以下代码来实现:
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 来实现呢?