对两个数组(值、键)进行排序,然后对键进行排序 [英] Sorting two arrays (values,keys), then sorting the keys

查看:35
本文介绍了对两个数组(值、键)进行排序,然后对键进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一个看似简单的问题,但目前我无法解决.

I have what seems to be a simple problem but I can't figure it out so far.

假设我有两个数组:

int[] values = {10,20,20,10,30};
int[] keys = {1,2,3,4,5};

Array.Sort(values,keys);

然后数组看起来像这样:

Then the arrays would look like this:

values = {10,10,20,20,30};
keys = {4,1,2,3,5};

现在,我想做的是让键也按第二优先级排序,键数组看起来像这样:

Now, what I want to do is make it so that the keys are also sorted in second priority so the key array to look like this:

keys = {1,4,2,3,5};

注意 1 和 4 的值切换了,值数组的顺序没有改变.

Notice the 1 and 4 values are switched and the order of the value array has not changed.

推荐答案

如果就地排序"对你来说不是绝对必要的,我建议使用OrderBy:

If an "in-place sorting" is not strictly necessary for you, I suggest to use OrderBy:

var sortedPairs = values.Select((x, i) => new { Value = x, Key = keys[i] })
                        .OrderBy(x => x.Value)
                        .ThenBy(x => x.Key)
                        .ToArray(); // this avoids sorting 2 times...
int[] sortedValues = sortedPairs.Select(x => x.Value).ToArray();
int[] sortedKeys = sortedPairs.Select(x => x.Key).ToArray();

// Result:
// sortedValues = {10,10,20,20,30};
// sortedKeys = {1,4,2,3,5};

这篇关于对两个数组(值、键)进行排序,然后对键进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆