Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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"
like image 841
Ramie Avatar asked Nov 20 '25 01:11

Ramie


2 Answers

int[] keys = partitioned.Select(pairs => pairs.Select(pair => pair.Key).ToArray())
    .ToArray();
string[] values = partitioned.Select(pairs => pairs.Select(pair => pair.Value).ToArray())
    .ToArray();
like image 61
Servy Avatar answered Nov 21 '25 14:11

Servy


Just to get you started:

    var list = new List<KeyValuePair<int, int>>();
    var key = new int[list.Count];
    var values = new int[list.Count];
    for (int i=0; i < list.Count ;i++)
    {
        key[i] = list[i].Key;
        values[i] = list[i].Value;
    }
like image 36
lboshuizen Avatar answered Nov 21 '25 14:11

lboshuizen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!