简体   繁体   English

如何反转 Array.Sort 的方向 - C#

[英]How to reverse the direction of Array.Sort - C#

I have a simple string array, with number 1 - 10, that I'm sorting with the following:我有一个简单的字符串数组,编号为 1 - 10,我正在使用以下内容进行排序:

Array.Sort(StringArray, StringComparer.InvariantCulture);

My questions is, how can I change the direction of the sort from 1 - 10 ascending, to be come 10 - 1 descending?我的问题是,如何将排序的方向从 1 - 10 升序更改为 10 - 1 降序?

There are a number of options.有多种选择。 Here is the most common I use . 这是我最常用的

Linq over a List can also be used. Linq over a List 也可以使用。

// 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 + " "); 
        } 
    } 
}

or或者

// 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 + " "); 
        } 
    } 
} 

If you want to sort the numbers in C# using Array methods, try this:如果要使用数组方法对 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

Just found this... seems to work great.刚刚发现这个......似乎工作得很好。

Array.Reverse(StringArray);   

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM