简体   繁体   中英

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

I need to convert an integer array to a list of KeyValuePair where the string can be an empty string. What would be an efficient and elegant way to do this?

So from this:

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

to this:

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, ""));

Obviously there are many ways to do this, starting from a for loop but I'm looking for preferably a single line of code, perhaps a linq statement if possible.

Something like this:

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

Or also possible:

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

Which will create a dictionary which basically IS a list of KeyValue-pairs.

Try this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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