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

cra*_*ake 0 c# linq keyvaluepair

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

所以从这个:

int[] ints = new int[] { 1, 2, 3 };
Run Code Online (Sandbox Code Playgroud)

对此:

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, ""));
Run Code Online (Sandbox Code Playgroud)

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

Him*_*ere 7

像这样的东西:

var res = ints.Select(x => new KeyValuePair<int, string>(x, "")).ToList();
Run Code Online (Sandbox Code Playgroud)

或者也可能:

var dict = ints.ToDictionary(x => x, x => "")
Run Code Online (Sandbox Code Playgroud)

这将创建一个基本上是KeyValue对列表的字典.