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.

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

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.
@SebastianWidz - My first answer works just fine with keys.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.