OneBite.Dev - Coding blog in a bite size

Sort Items In Array By Asc In C#

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

Array manipulation is a critical skill for any C# developer. In this simple article, we are going to learn how to sort items in an array in ascending order using C#.

Code Snippet: Array Sorting in Ascending Order

Here is the code snippet to sort the items of an array in ascending order in C#.

using System;

class Program
{
    static void Main(string[] args)
    {
        int[] numbers = { 5, 8, 1, 4, 9, 2 };
        Array.Sort(numbers);
        Console.WriteLine("Array in ascending order: " + String.Join(", ", numbers));
    }
}

Code Explanation for Array Sorting in Ascending Order

Let’s break down the code snippet above and explain how it works in a step by step manner.

  1. We begin with the using System; directive. This directive allows our class to use classes from the System namespace.
using System;
  1. The next line class Program is the start of our class definition. In this case, we are creating a class named Program.
class Program
  1. The first line inside the Program class is static void Main(string[] args). This is the main method of our program, which is the entry point for the application.
static void Main(string[] args)
  1. Inside the Main method, we first declare an integer array numbers and initialize it with some values.
int[] numbers = { 5, 8, 1, 4, 9, 2 };
  1. The next line Array.Sort(numbers); is where the sorting of numbers happens. The Sort method from the Array class will sort the elements of the numbers array in ascending order.
Array.Sort(numbers);
  1. Finally, we print the sorted array in the console using Console.WriteLine. The String.Join method concatenates each element of the sorted numbers array into a string with , as a separator.
Console.WriteLine("Array in ascending order: " + String.Join(", ", numbers));

So, after you run this program, you will see “Array in ascending order: 1, 2, 4, 5, 8, 9” in the console.

That’s all there is to it! With just a few lines of code, you can sort the items of an array in ascending order in C#.

c-sharp