转换列表 到列表 (Convert List to List

2019-06-27 02:08发布

可能重复:
有没有一种办法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实现它的另一种方式?

Answer 1:

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


Answer 2:

我不建议在这里使用LINQ,因为实在是没有理由,你不使用LINQ,而只是使用普通的获得任何for循环,并在每次迭代由两个增加您的计数变量:

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]));
}

请注意,我开始我的索引与1所以我没有碰到一个例外的情况下访问一个无效的索引项的数量input为奇数,即,如果input与价值观的“半双”结束。



Answer 3:

你可以这样做:

IEnumerable<KeyValuePair<string, string>> list = 
        input.Where((s, i) => i % 2 == 0)
             .Select((s, i) => new KeyValuePair<string, string>(s, input.ElementAt(i * 2 + 1)));


Answer 4:

你可以使用LINQ聚合()函数(代码长于一个简单的循环):

var result = 
input.Aggregate(new List<List<string>>(),
                (acc, s) =>
                {
                    if (acc.Count == 0 || acc[acc.Count - 1].Count == 2)
                        acc.Add(new List<string>(2) { s });
                    else
                        acc[acc.Count - 1].Add(s);
                    return acc;
                })
                .Select(x => new KeyValuePair<string, string>(x[0], x[1]))
                .ToList();

NB
这个工程即使您最初的输入变为通用IEnumerable<string>并没有具体一个List<string>



文章来源: Convert List to List> using Linq [duplicate]
标签: c# linq lambda