1

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?

3 Answers 3

2

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
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

Just found this ... seems to work great.

Array.Reverse(StringArray);   

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.