Sorting an array related to another array

Array.Sort has an overload that accepts two arrays; one for the keys, and one for the items. The items of both are sorted according to the keys array:

int[] keys = { 1, 4, 3, 2, 5 };
string[] items = { "abc", "def", "ghi", "jkl", "mno" };
Array.Sort(keys, items);
foreach (int key in keys) {
    Console.WriteLine(key); // 1, 2, 3, 4, 5
}
foreach (string item in items) {
    Console.WriteLine(item); // abc, jkl, ghi, def, mno
}

So in your case, it sounds like you want:

Array.Sort(y,x); // or Sort(x,y); - it isn't  100% clear

Leave a Comment