Sebastian Widz
Sebastian Widz

Reputation: 2072

How to sort array of keys based on values stored in separate array

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.

Upvotes: 2

Views: 72

Answers (1)

Enigmativity
Enigmativity

Reputation: 117027

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

Upvotes: 5

Related Questions