I am trying to sort different item arrays based on one key array. The following simple code represents my more complex code:
int[] first = new int[] { 1, 9, 2, 3, 8, 4, 5 };
string[] second = new string[] { "one", "nine", "two", "three", "eight", "four", "five" };
int[] temp = first;
Array.Sort(temp, second);
foreach (int v in temp)
{
Debug.WriteLine(v.ToString());
}
foreach (string v in second)
{
Debug.WriteLine(v);
}
int[] third = new int[] { 11, 99, 22, 33, 88, 44, 55 };
foreach (int v in first)
{
Debug.WriteLine(v.ToString());
}
Array.Sort(first, third);
foreach (int v in first)
{
Debug.WriteLine(v.ToString());
}
foreach (int v in third)
{
Debug.WriteLine(v);
}
The arrays, called 'second' and 'third', should be sorted based on the ordering of array 'first'. I found that I can do this with:
Array.Sort(first, second)
This perfectly works, until I add another Array.Sort to sort 'third'. Since I want to keep 'first' as key array for other sorting actions, I use a temporary array called 'temp' to save the initial sequence for 'first' so that I can reuse each time. When I reuse first to also sort 'third' using Array.Sort(first, third), the sorting does not work (see output). It seems that 'first' gets sorted together with 'temp' during the first Array.Sort, even though it is not in the command.
Output:
1
2
3
4
5
8
9
one
two
three
four
five
eight
nine
1 //--> 'first' before it is used in Array.Sort, so it seems already sorted
2
3
4
5
8
9
1
2
3
4
5
8
9
11 //--> 'third' does not get sorted because 'first' seemed already sorted
99
22
33
88
44
55
How do I make sure that my key array does not get sorted so that I can use it multiple times?