OneBite.Dev - Coding blog in a bite size

Sort Items In Array By Desc In C#

Code snippet for how to Sort Items In Array By Desc In C# with sample and detail explanation

In C#, there are times where we may want to sort an array of elements in descending order, i.e., from largest to smallest. This article will provide an accessible guide to achieve this task using C#.

Code snippet: Sorting an Array in Descending Order

We have the main function of our program, which is tasked with defining an array of integers (int) and sorting the array:

using System;
using System.Linq;

class Program
{
    static void Main()
    {
        int[] arr = {1, 5, 2, 8, 6, 3, 7};
        
        Console.WriteLine("Initial array:");
        foreach (var item in arr)
        {
            Console.Write(item + " ");
        }

        arr = SortingInDescendingOrder(arr);

        Console.WriteLine("\nSorted array:");
        foreach (var item in arr)
        {
            Console.Write(item + " ");
        }
    }

    static int[] SortingInDescendingOrder(int[] array)
    {
        Array.Sort(array);
        Array.Reverse(array);
        return array;
    }
}

Code Explanation for Sorting an Array in Descending Order

This program in C# is succinct but effective at demonstrating how to sort items in an array in descending order. Here’s a step-by-step breakdown of the different elements involved:

Step 1: The main method of the program creates an integer array int[] arr that contains seven different elements.

Step 2: The Console.WriteLine and foreach loop print the initial array to the console. This is done by looping through each item in the array and printing it to the console.

Step 3: The SortingInDescendingOrder function is called on the array. Inside this function, we first use the Array.Sort method to sort the array in ascending order.

Step 4: After sorting the array in ascending order, we then use the Array.Reverse method which will reverse the array, making it in descending order.

Step 5: Finally this function SortingInDescendingOrder returns our sorted array which then gets printed to the console.

Overall, this script demonstrates a simple and effective way to sort an array into descending order. If you wanted the array in ascending order, you’d skip the Array.Reverse method.

c-sharp