Convert KeyValuePair<int,string> to an int[] array and string[] array

Ramie picture Ramie · Jan 18, 2013 · Viewed 7k times · Source
KeyValuePair<int, string>[][] partitioned = SplitVals(tsRequests.ToArray());

Don't worry too much about the method i use; lets just say i get a jagged array of KeyValuePairs that are split equally into different arrays.

foreach (KeyValuePair<int, string>[] pair in partitioned)
{
    foreach (KeyValuePair<int, string> k in pair)
    {
    }
}

I need to know how i can efficiently get the ints in an int array, and the strings in a seperate string array from the array of keyvaluepairs. That way both of the indexes match eachother in seperate arrays.

For example, after i split it into an int[] array and a string[] array,

intarray[3] must match stringarray[3] just like it did in the keyvaluepair.

Lets say i have a jagged array with KVP like:

    [1][]<1,"dog">, <2,"cat">
    [2][]<3,"mouse">,<4,"horse">,<5,"goat">
    [3][]<6,"cow">

I need this to turn into during each iteration

    1. 1,2 / "dog","cat"
    2. 3,4,5 / "mouse", "horse", "goat"
    3. 6 / "cow"

Answer

Servy picture Servy · Jan 18, 2013
int[] keys = partitioned.Select(pairs => pairs.Select(pair => pair.Key).ToArray())
    .ToArray();
string[] values = partitioned.Select(pairs => pairs.Select(pair => pair.Value).ToArray())
    .ToArray();