I have this arrays:
int[] a = {5, 2, 3};
int[] b = {4, 1, 2};
string[] c = {"John", "Peter", "Max"};
I need to sort the values of, say, the second array (b[]), but in relation with the other two arrays, so that they get sorted accordingly. For example, 1 will come first as it’s the lowest number, and since 1 in b[] relates to 2 in a[] and "Peter" in c[], then it means that 2 and "peter" will also move to the first sort position too. The same goes for the other two columns; observe:
int[] a = {2, 3, 5};
int[] b = {1, 2, 4};
string[] c = {"Peter", "Max", "John"};
How would I do this?
I think I understand what you are saying. You want to sort array
aandcbased on the values ofb.You can sort an array by another array using
Array.Sortwhich lets you specify another array for keys for example:This will output your expected values. Note that we use
ToArrayto create a copy of the arrays when sorting by key, that’s becauseArray.Sortsorts both they keys and the values, which we don’t want. We don’t sort the Keys (bin this case) till the end.That’s how we solve your immediate problem. However, gathered from the comments, you are trying to sort tabular data. When your data has some structure to it, say like this:
It gets a lot easier.
This uses
LINQ, which is perfect for what you are trying to do.