- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Sort an array in descending order using C#
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
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
Advertisements