Sort an array in descending order using C#

CsharpProgrammingServer Side Programming

Declare an array and initialize −

int[] arr = new int[] {
   87,
   23,
   65,
   29,
   67
};

To sort, use the Sort() method and CompareTo() to compare and display in decreasing order −

Array.Sort < int > (arr, new Comparison < int > ((val1, val2) => val2.CompareTo(val1)));

Let us see the complete code −

Example

 Live Demo

using System;
using System.Collections.Generic;
using System.Text;

public class Demo {
   public static void Main(string[] args) {
      int[] arr = new int[] {
         87,
         23,
         65,
         29,
         67
      };

      // Initial Array
      Console.WriteLine("Initial Array...");
      foreach(int items in arr) {
         Console.WriteLine(items);
      }
      Array.Sort < int > (arr, new Comparison < int > ((val1, val2) => val2.CompareTo(val1)));

      // Sorted Array
      Console.WriteLine("Sorted Array in decreasing order...");
      foreach(int items in arr) {
         Console.WriteLine(items);
      }
   }
}

Output

Initial Array...
87
23
65
29
67
Sorted Array in decreasing order...
87
67
65
29
23
raja
Published on 21-Aug-2018 13:05:34
Advertisements