我有一个int数组,我必须通过降序排序.
因为我没有找到任何方法来按降序对数组进行排序.目前我按降序对数组进行排序,如下所示
int[] array = new int[] { 3, 1, 4, 5, 2 };
Array.Sort<int>( array );
Array.Reverse( array );
Run Code Online (Sandbox Code Playgroud)
现在,问题是.在c#中有更好的方法吗?
Ily*_*gin 62
使用LINQ OrderByDescending
方法.它返回IOrderedIEnumerable<int>
,如果需要,可以将其转换回Array.通常,List<>
s比s更具功能Array
.
array = array.OrderByDescending(c => c).ToArray();
Run Code Online (Sandbox Code Playgroud)
JYL*_*JYL 56
根据排序顺序,您可以执行以下操作:
int[] array = new int[] { 3, 1, 4, 5, 2 };
Array.Sort<int>(array,
new Comparison<int>(
(i1, i2) => i2.CompareTo(i1)
));
Run Code Online (Sandbox Code Playgroud)
... 或这个 :
int[] array = new int[] { 3, 1, 4, 5, 2 };
Array.Sort<int>(array,
new Comparison<int>(
(i1, i2) => i1.CompareTo(i2)
));
Run Code Online (Sandbox Code Playgroud)
i1和i2正好相反.
Ale*_*Aza 12
对于按降序就地排序:
int[] numbers = { 1, 2, 3 };
Array.Sort(numbers, (a, b) => b.CompareTo(a));
Run Code Online (Sandbox Code Playgroud)
对于异地排序(不更改输入数组):
int[] numbers = { 1, 2, 3 };
var sortedNumbers = numbers.OrderByDescending(x => x).ToArray();
Run Code Online (Sandbox Code Playgroud)
当然,您可以自定义排序.
您需要将Sort()作为委托给它将用于排序的比较方法.
使用匿名方法:
Array.Sort<int>( array,
delegate(int a, int b)
{
return b - a; //Normal compare is a-b
});
Run Code Online (Sandbox Code Playgroud)
阅读更多相关信息:
排序数组
MSDN - Array.Sort方法(T [],比较)