转换列表<串GT;列出< KeyValuePair<字符串,字符串>>使用LINQ [英] Convert List<string> to List<KeyValuePair<string, string>> using Linq

查看:194
本文介绍了转换列表<串GT;列出< KeyValuePair<字符串,字符串>>使用LINQ的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:结果
是否有一个LINQ方式,从键/值对列表去一个字典?






假设我有一个列表<串> 如下:

  VAR输入=新的List<串>()
{
键1,
值1,
键2,
值2,
KEY3,
值3,
KEY4,
VALUE4
};

根据这个名单,我想转换为列表< KeyValuePair<字符串,字符串>> ,其原因是为了让相同的密钥,这就是为什么我不使用词典

 无功输出=新的List< KeyValuePair<字符串,字符串>>()
{
新KeyValuePair<字符串,字符串>(KEY1,值1),
新KeyValuePair<字符串,字符串>(KEY2,值2),
新KeyValuePair<字符串,字符串>(KEY3,值3),
新KeyValuePair<字符串,字符串> (KEY4,值4)
};



我可以用下面的代码实现:

  VAR键=新的List<串GT;(); 
VAR值=新的List<串GT;();

为(INT指数= 0;指数 - LT; input.Count;指数++)
{
如果(索引%2 == 0)keys.Add(输入[指数] );
,否则values.Add(输入[指数]);
}

VAR的结果= keys.Zip(值(键,值)=>
新KeyValuePair<字符串,字符串>(键,值));



不过感觉,这是不使用循环最好的办法,有没有另一种方式,我们可以使用内置的LINQ实现呢?


解决方案

  VAR输出= Enumerable.Range(0,input.Count / 2)
。选择(I => Tuple.Create(输入[我* 2],输入[我* 2 + 1 ))
.ToList();


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?

解决方案

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

这篇关于转换列表&LT;串GT;列出&LT; KeyValuePair&LT;字符串,字符串&GT;&GT;使用LINQ的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆