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

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

问题描述

我有 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 进行排序 -> a = {20, 120, 60, 50, 30, 40}

I want to sort a by b's index -> a = {20, 120, 60, 50, 30, 40}

如果我也有字符串数组 c ->c = {"b", "u", "r", "s", "a", "1"}

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

我想按 b 的索引对 c 进行排序 -> 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[] keys, TValue[] items) 接受两个输入数组,一个是键数组,另一个是使用这些键排序的项数组.在这里,对你来说,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的项目进行排序.

will use the keys of b to sort the items of a.

我想按 b 的索引对 c 进行排序 -> c = {"1", "b", "u", "r", "a", "s"}

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

不清楚你的意思.在使用 ba 进行排序的同时?如果是这样,这很容易,因为我们仍然可以使用上述内容.将 ac 压缩成一个 Tuple 数组.

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();

那么:

Array.Sort(b, d);

如上.然后提取碎片:

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);

现在您可以使用 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();

等等.根据需要.

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

Possibly some minor coding errors here. No compiler handy.

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

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