如何两个数组由相同的索引排序? [英] How to sort two arrays by same index?

查看:118
本文介绍了如何两个数组由相同的索引排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个阵列。我想通过同样的指数对它们进行排序。比如我有这些:

I have 2 arrays. I want to sort them by same index number. For example I have these:

int[] a = {120, 60, 50, 40, 30, 20};
int[] b = {12, 29, 37, 85, 63, 11};

Array.Sort(b); // Now, b is -> b = {11, 12, 29, 37, 63, 85}



我要作为排序依据b的指数 - > A = {20,120,60,50,30,40}

如果我有也字符串数组 C - > C = {B,U,R,S,一个,1}

If I have also string array c -> c = {"b", "u", "r", "s", "a", "1"}

我希望通过b的指数进行排序ç - > C = {1,b,U,R,A,S}

I want to sort c by b's index -> c = {"1", "b", "u", "r", "a", "s"}

我怎样才能做到这一点?提前
谢谢,
问候

How can I do this? Thanks in advance, Regards.

推荐答案

使用的 的Array.Sort< TKEY的,TValue>(TKEY的[]键,TValue []项目) 接受两个输入数组,一个是键阵列,另一种是项目阵列使用这些键进行排序。在这里,对你来说, B 是键和 A 为您的项目。

Use Array.Sort<TKey, TValue>(TKey[] keys, TValue[] items) that accepts two input arrays, one is the array of keys, the other is the array of items to sort using those keys. Here, for you, b is your keys and a is your items.

因此:

Array.Sort(b, a);



将使用的按键b 排序的项目 A

我要排序 ç b 的指数 - > C = {1,b,U, R,A,S}

I want to sort c by b's index -> c = {"1", "b", "u", "r", "a", "s"}

不太清楚你的意思到底是什么。同时,你的排序 A 使用 B ?如果是这样,这很容易,因为我们仍然可以使用上面。邮编 A C 元组℃的单一阵列,整型,字符串>

Not clear exactly what you mean. At the same time as you sort a using b? If so, it's easy as we can still use the above. Zip a and c into a single array of Tuple<int, string>.

var d = a.Zip(c, (x, y) => Tuple.Create(x, y)).ToArray();



然后:

Then:

Array.Sort(b, d);



如上。然后抽取部分:

as above. Then extract the pieces:

a = d.Select(z => z.Item1).ToArray();
c = d.Select(z => z.Item2).ToArray();



另外,如果您需要使用相同的密钥集排序大量数组:

Alternatively, if you need to sort a lot of arrays using the same set of keys:

int[] indexes = Enumerable.Range(0, b.Length).ToArray();
Array.Sort(b, indexes);

现在你可以使用指标来排序的所有你需要的阵列。例如:

Now you can use indexes to sort all the arrays you need. For example:

a = indexes.Select(index => a[index]).ToArray();
c = indexes.Select(index => c[index]).ToArray();



等。根据需要。

etc. as needed.

这里可能一些小的编码错误。没有编译器方便。

Possibly some minor coding errors here. No compiler handy.

这篇关于如何两个数组由相同的索引排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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