Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order an array using another array as indexes C# [duplicate]

Tags:

arrays

c#

sorting

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?

like image 935
simonalexander2005 Avatar asked Dec 22 '22 01:12

simonalexander2005


1 Answers

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)

like image 171
Marc Gravell Avatar answered Feb 23 '23 09:02

Marc Gravell