stepanex stepanex - 18 days ago 5
C# Question

c# Sorting 2 arrays while having same number in index

I have 2 arrays:

int[] x1 = { 1, 2, 1, 2 };
int[] x2 = { 3, 1, 2, 3 };


and after sorting them with

Array.Sort(x1, x2);


the arrays look like this:

int[] x1 = { 1, 1, 2, 2 };
int[] x2 = { 3, 2, 1, 3 };


But I want array x2 to look like this:

{3,2,3,1}


The problem is, if .sort sees the same number in first array(index, here x1) it will just sort the same numbers as they went after each other and won't looks at the x2 array, which I want it to do. So, is it somehow possible to sort it this way?

Answer

Assuming you have 2 arrays like this:

int[] x1 = { 1, 2, 1, 2}; 
int[] x2 = {3, 1, 2, 3};

The first thing I would do is to join them together and apply the ordering. This is pretty simple with some Linq:

var joined = x1.Zip(x2, (a, b) => new { a, b })
   .OrderBy(x => x.a)
   .ThenByDescending(x => x.b);

Now you can split them back up into the constituent arrays:

x1 = joined.Select(x => x.a).ToArray();
x2 = joined.Select(x => x.b).ToArray();