Search code examples
c#arrayssortingranking

How can I sort (rank) the elements of an array, according to another array?


I have to arrays in my C# project whose elements with the same index have a relationship:

The simplified example is as follows:

Array_1 [0] =902;
Array_1 [1] =109;
Array_1 [2] =205;
Array_1 [3] =187;
Array_1 [4] =440;
Array_1 [5] =508;


Array_2 [0] ="Ford";
Array_2 [1] ="Opel";
Array_2 [2] ="Kia";
Array_2 [3] ="Renault";
Array_2 [4] ="BMW";
Array_2 [5] ="Toyota";

I have to sort Array-2 according to the value ranking of Array_1(low to High). The result will be written into Array_2_sorted. That means: Array_1's lowest value is Array_1[1] (109) --> so Array_2[1] (Opel) should be Array_2_sorted[0]

the next higher value is Array_1[3] (187) --> so Array_2[3] (Renault) should be Array_2_sorted[1]

the next higher value is Array_1[2] (205) --> so Array_2[2] (Kia) should be Array_2_sorted[2]

the next higher value is Array_1[4] (440) --> so Array_2[4] (BMW) should be Array_2_sorted[3]

...

How can I do such a sorting (ranking) of an array in C#?


Solution

  • Array.Sort offers such functionality.

    https://learn.microsoft.com/en-us/dotnet/api/system.array.sort?view=net-7.0#system-array-sort(system-array-system-array)

    Sorts a pair of one-dimensional Array objects (one contains the keys and the other contains the corresponding items) based on the keys in the first Array using the IComparable implementation of each key.

    So simply call

    Array.Sort(Array_1, Array_2);
    

    See here:

    https://dotnetfiddle.net/mKIM7o