so if I have an array of characters
char[] chars = new char[]{'f','a','d','e','c','b'};
and another array of integers that say what the sort order is:
int[] sortOrder = new int[]{5,1,4,5,3,2};
how could I sort the data in the chars array, using the values in the sortOrder array to determine the order? In the above example, the sorted array would look like
{'a','b','c','d','e','f'}
(the 'd' moved to position 4, the 'a' to position 1, etc. Where the 5 is repeated, the order doesn't matter.)
I know I could do it by creating a third array, but ideally I would like to do it using LinQ (the .Sort) method or something similar, because there may be duplicated values in the sortOrder array.
I guess effectively I want to sort the sortOrder array (easy using sortOrder.Sort()), but then get it to sort the chars array with the exact same changes, somehow?
There is an overload of Array.Sort
that does exactly that...
Array.Sort(sortOrder, chars);
(note that this actually sorts both arrays in parallel - i.e. it sorts the keys, and makes the same swaps to the target array)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With