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

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

问题描述

我有什么似乎是一个简单的问题,但我不能弄明白为止。

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.

推荐答案

如果一个就地分拣不是绝对必要的你,我建议使用排序依据

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天全站免登陆