如何用同一个索引对两个数组进行排序?
我有2个arrays。 我想用相同的索引号对它们进行排序。 例如,我有这些:
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", "a", "1"}
我想用b的索引对c进行排序 – > c = {"1", "b", "u", "r", "a", "s"}
我怎样才能做到这一点? 提前谢谢,问候。
使用接受两个输入数组的Array.Sort
,一个是键数组,另一个是使用这些键排序的项数组。 在这里,对你而言, b
是你的钥匙,而a
是你的物品。
从而:
Array.Sort(b, a);
将使用b
的键对b
的项进行排序。
我想用
b
的索引对c
进行排序 – >c = {"1", "b", "u", "r", "a", "s"}
不清楚你的意思。 在你使用b
排序a
? 如果是这样,它很容易,因为我们仍然可以使用上述内容。 将a
和c
压缩为单个Tuple
数组。
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();
或者,如果您需要使用同一组键对许多数组进行排序:
int[] indexes = Enumerable.Range(0, b.Length).ToArray(); Array.Sort(b, indexes);
现在,您可以使用indexes
对所需的所有arrays进行排序。 例如:
a = indexes.Select(index => a[index]).ToArray(); c = indexes.Select(index => c[index]).ToArray();
等等。
这里可能有一些小的编码错误。 没有编译器方便。
上述就是C#学习教程:如何用同一个索引对两个数组进行排序?分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
// a dirty and inefficient way of doing it, // but should give you a heads up to get started // you obviously dont want to modify array b, so making a copy int[] c = Arrays.copyOf(b, b.length); // now apply a sort on 'c' and apply the same operation on 'a' when modifying 'c' // -> applying a bubble sort - > inefficient for( int i = 0; i < c.length ; i ++) { for( int j = 0 ; j < c.length - 1; j ++) { if(c[j] > c [j+1]) { c[j] = c[j] + c[j+1]; c[j+1] = c[j] - c[j+1]; c[j] = c[j] - c[j+1]; // apply the same to a a[j] = a[j] + a[j+1]; a[j+1] = a[j] - a[j+1]; a[j] = a[j] - a[j+1]; } } }
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/999728.html