繁体   English   中英

如何将int数组转换为List <KeyValuePair<int, string> &gt;?

[英]How to convert int array to List<KeyValuePair<int, string>>?

我需要将整数数组转换为KeyValuePair列表,其中字符串可以是空字符串。 什么是有效而优雅的方法?

所以从这个:

int[] ints = new int[] { 1, 2, 3 };

对此:

List<KeyValuePair<int, string>> pairs = new List<KeyValuePair<int, string>>();
pairs.Add(new KeyValuePair<int, string>(1, ""));
pairs.Add(new KeyValuePair<int, string>(2, ""));
pairs.Add(new KeyValuePair<int, string>(3, ""));

显然,有很多方法可以做到这一点,从for循环开始,但我正在寻找的最好是一行代码,如果可能的话,可能是linq语句。

像这样:

var res = ints.Select(x => new KeyValuePair<int, string>(x, "")).ToList();

或者也可以:

var dict = ints.ToDictionary(x => x, x => "")

它将创建一个字典,该字典基本上是KeyValue对的列表。

尝试这个:

int[] ints = new int[] { 1, 2, 3 };
List<KeyValuePair<int, string>> pairs = ints.Select(i => new KeyValuePair<int, string>(i, i.ToString())).ToList();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM