如何根据存储在单独数组中的值对键数组进行排序

时间:2016-01-12 06:55:53

标签: c# sorting compareto

如何根据存储在C#

中单独数组中的值对键数组进行排序

实施例

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

我想根据vals数组中的值对键数组进行排序。在keys数组中获得以下顺序:

4, 2, 3, 7, 1

我试图做以下

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

但是我收到以下错误:

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]'.

我猜a和b参数是指键值而不是键数组中的键索引。

1 个答案:

答案 0 :(得分:5)

这对你有用吗?

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

这给出了这个结果:

result