Reputation: 481
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.
Upvotes: 1
Views: 3925
Reputation: 13960
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();
Upvotes: 3
Reputation: 37000
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.
Upvotes: 8