Order an array using another array, like C # indices

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 sort order is:

 int[] sortOrder = new int[]{5,1,4,5,3,2}; 

how can I sort the data in an array of characters using the values ​​in the sortOrder array to determine the order? In the above example, the sorted array will look like

 {'a','b','c','d','e','f'} 

("d" moved to position 4, "a" to position 1, etc., where 5 is repeated, the order does not matter.)

I know I can do this by creating a third array, but ideally I would like to do this using the LinQ (.Sort) method or something similar, because values ​​in the sortOrder array can be duplicated.

I think I want to sort the sortOrder array (just using sortOrder.Sort ()), but then try to sort the character array with the same changes, somehow?

+4
source share
1 answer

There is an Array.Sort overload that does just that ...

 Array.Sort(sortOrder, chars); 

(note that this actually sorts both arrays in parallel - i.e. sorts the keys and makes the same swaps in the target array)

+11
source

Source: https://habr.com/ru/post/1314556/


All Articles