2

How to sort an array of keys based on values stored in a separate array in C#

Example

int[] keys = new int[] {1, 2, 3, 4, 7};
double[] vals = new double[] {0.5, 0.2, 0.3, 0.1, 0.4};

I would like to sort keys array based on values in vals array ie. get the following order in keys array:

4, 2, 3, 7, 1

I was trying to do the following

Array.Sort(keys, (a, b) => vals[a].CompareTo(vals[b]));

But I get the following error:

Additional information: Unable to sort because the IComparer.Compare() method returns inconsistent results. Either a value does not compare equal to itself, or one value repeatedly compared to another value yields different results. IComparer: 'System.Array+FunctorComparer`1[System.Int32]'.

I guess a and b parameters refer to key values rather than to key indexes in keys array.

Sebastian Widz
  • 1,962
  • 4
  • 26
  • 45

1 Answers1

5

Does this work for you?

int[] sorted =
    vals
        .Zip(keys, (v, i) => new { v, i })
        .OrderBy(x => x.v)
        .Select(x => x.i)
        .ToArray();

This gives this result:

result

Enigmativity
  • 113,464
  • 11
  • 89
  • 172
  • Thanks for answer, But it is not exactly what I wanted to achieve. I updated my question. This is not just indexing starting from 1. This should rather be understood as keys. Sorry for this missunderstanding and please see my updated example. – Sebastian Widz Jan 12 '16 at 07:06
  • @SebastianWidz - My first answer works just fine with `keys`. – Enigmativity Jan 12 '16 at 07:12