[英]How to reverse the direction of Array.Sort - C#
我有一個簡單的字符串數組,編號為 1 - 10,我正在使用以下內容進行排序:
Array.Sort(StringArray, StringComparer.InvariantCulture);
我的問題是,如何將排序的方向從 1 - 10 升序更改為 10 - 1 降序?
有多種選擇。 這是我最常用的。
// C# program sort an array in
// decreasing order using
// CompareTo() Method
using System;
class GFG {
// Main Method
public static void Main()
{
// declaring and initializing the array
int[] arr = new int[] {1, 9, 6, 7, 5, 9};
// Sort the arr from last to first.
// compare every element to each other
Array.Sort<int>(arr, new Comparison<int>(
(i1, i2) => i2.CompareTo(i1)));
// print all element of array
foreach(int value in arr)
{
Console.Write(value + " ");
}
}
}
或者
// C# program sort an array in decreasing order
// using Array.Sort() and Array.Reverse() Method
using System;
class GFG {
// Main Method
public static void Main()
{
// declaring and initializing the array
int[] arr = new int[] {1, 9, 6, 7, 5, 9};
// Sort array in ascending order.
Array.Sort(arr);
// reverse array
Array.Reverse(arr);
// print all element of array
foreach(int value in arr)
{
Console.Write(value + " ");
}
}
}
如果要使用數組方法對 C# 中的數字進行排序,請嘗試以下操作:
int[] arr = new int[] {1, 2, 3, 4, 5,6, 7, 8, 9, 10};
Array.Sort(arr); //1 2 3 4 5 6 7 8 9 10
Array.Reverse(arr); //10 9 8 7 6 5 4 3 2 1
剛剛發現這個......似乎工作得很好。
Array.Reverse(StringArray);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.