1

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.

crazysnake
  • 451
  • 2
  • 7
  • 18

2 Answers2

8

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.

MakePeaceGreatAgain
  • 35,491
  • 6
  • 60
  • 111
3

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();
Oscar
  • 13,594
  • 8
  • 47
  • 75