[英]C# array.sort() for multiple arrays in Descending order
I Have two arrays named weights and values. 我有两个名为权重和值的数组。 I wanted to sort Values based on the sorting of Weights.
我想根据权重排序对值进行排序。 That works perfectly fine by doing
通过这样做,效果很好
Array.Sort(Weights,Values);
This gives me arrays sorted in ascending order. 这给了我升序排列的数组。 I wanted to do the same sorting in Descending order.
我想按降序进行相同的排序。 Is there a better way to do without using
Array.Reverse(Weights) and Array.Reverse(Values)
有没有不使用
Array.Reverse(Weights) and Array.Reverse(Values)
的更好的方法
You'll have to use this overload and provide a custom IComparer<T>
. 您将必须使用此重载并提供一个自定义
IComparer<T>
。 The relatively new Comparer<T>.Create
method makes this a lot easier because you can simply turn a delegate or lambda expression into an IComparer<T>
without having to code a full implementation yourself. 相对较新的
Comparer<T>.Create
方法使此操作变得容易Comparer<T>.Create
因为您可以简单地将委托或lambda表达式转换为IComparer<T>
而不必自己编写完整的实现。 It's not clear from the question what the datatype of Weights
and Values
are, but here's an example using double[]
and int[]
respectively: 从这个问题尚不清楚,
Weights
和Values
的数据类型是什么,但这是分别使用double[]
和int[]
的示例:
var Weights = new [] { 1.7, 2.4, 9.1, 2.1, };
var Values = new [] { 7, 9, 5, 3, };
Array.Sort(Weights, Values, Comparer<double>.Create((x, y) => y.CompareTo(x)));
And just for fun, here's a solution using LINQ: 只是为了好玩,这是使用LINQ的解决方案:
var pairs = Weights.Zip(Values, Tuple.Create);
var orderedPairs = pairs.OrderByDescending(x => x.Item1);
I'd also recommend that you consider using a class to store weights and values together rather than as two separate arrays. 我还建议您考虑使用一个类将权重和值存储在一起,而不是作为两个单独的数组存储。
First, create a structure that holds the corresponding items. 首先,创建一个包含相应项目的结构。
var items =
Weights
.Select((weight, index) =>
new
{
Weight = weight,
Value = Values[index]
}
)
.OrderByDescending(item => item.Weight)
.ToArray();
Then you can get the sorted array back: 然后,您可以返回排序后的数组:
Weights = items.Select(item => item.Weight).ToArray();
Values = items.Select(item => item.Value).ToArray();
But you may also try one of the answers here: 但是您也可以在这里尝试答案之一:
Better way to sort array in descending order 更好的方法以降序对数组进行排序
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.