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.
- We begin with the
using System;
directive. This directive allows our class to use classes from theSystem
namespace.
using System;
- The next line
class Program
is the start of our class definition. In this case, we are creating a class namedProgram
.
class Program
- The first line inside the
Program
class isstatic 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)
- Inside the
Main
method, we first declare an integer arraynumbers
and initialize it with some values.
int[] numbers = { 5, 8, 1, 4, 9, 2 };
- The next line
Array.Sort(numbers);
is where the sorting of numbers happens. TheSort
method from theArray
class will sort the elements of thenumbers
array in ascending order.
Array.Sort(numbers);
- Finally, we print the sorted array in the console using
Console.WriteLine
. TheString.Join
method concatenates each element of the sortednumbers
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#.