简体   繁体   中英

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:

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?

There are a number of options. Here is the most common I use .

Linq over a List can also be used.

// 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:

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);   

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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