level42
level42

Reputation: 987

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?

Upvotes: 1

Views: 4063

Answers (3)

Sahil Sharma
Sahil Sharma

Reputation: 1899

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

Upvotes: 2

Murray Foxcroft
Murray Foxcroft

Reputation: 13775

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

Upvotes: 1

level42
level42

Reputation: 987

Just found this ... seems to work great.

Array.Reverse(StringArray);   

Upvotes: 0

Related Questions