2

Code:

var list = new List<KeyValuePair<int, string[]>>();
list .Add(new KeyValuePair<int, string[]>(1, new string[] { "1", "One"}));
list .Add(new KeyValuePair<int, string[]>(2, new string[] { "2", "Two"}));
list .Add(new KeyValuePair<int, string[]>(3, new string[] { "3", "Three"}));
list .Add(new KeyValuePair<int, string[]>(4, new string[] { "4", "Four"}));

Need to select only the values from this list of KeyValuePairs and build an array. I tried this.

var values = list.Select(v => v.Value.ToList()).ToArray();

Expecting a string[] like this.

{"1", "One", "2", "Two", "3", "Three", "4", "Four"}

But it returns a List<string>[] like this

{{"1", "One"}, {"2", "Two"}, {"3", "Three"}, {"4", "Four"}}

Also tried

var values = list.Select(v => v.Value.ToArray()).ToArray();

But it returns string[][]. I can convert the string[][] to string[] but I want to do it directly using Linq.

I need to pass the expected array to another method. Please help.

Thanks!

Code.me
  • 281
  • 3
  • 13

2 Answers2

5

Use Enumerable.SelectMany like:

var values = list.SelectMany(v => v.Value).ToArray();

SelectMany will:

Projects each element of a sequence to an IEnumerable<T> and flattens the resulting sequences into one sequence.

Habib
  • 219,104
  • 29
  • 407
  • 436
2

Use SelectMany

 var values = list.SelectMany(v => v.Value).ToArray();
MRebai
  • 5,344
  • 3
  • 33
  • 52