Monday 30 October 2023

Arrays in C#

In C#, an array is a collection of elements of the same type that are stored in contiguous memory locations and can be accessed using an index. Arrays provide an efficient way of storing and accessing a fixed number of elements.

 Create an array 

There are multiple ways to create an array in C#. Here are a few examples.

Using the new keyword

  int[] numbers = new int[5];

The above code snippet creates an array called "intArray" to hold five integers. However, the elements of the Array are not yet initialized, and their values are undefined.

Using the new keyword with an array initializer

Arrays can also be initialized when they are declared by providing a list of comma-separated values enclosed in curly braces {}

  int[] intArray = new int[] {1, 2, 3, 4, 5};

  // or Simply
 
  int[] intArray = {1, 2, 3, 4, 5};

This creates an array called "intArray" with five elements and assigns the values 1, 2, 3, 4, and 5 to the elements of the Array.

Using the var keyword

  var myArray = new int[] {1, 2, 3, 4, 5};

This creates an array; the array type is inferred from the initializer, and the Array's name is myArray.

How To Sort Array In C#

The simplest way to sort an array in C# is using Array.Sort method. The Array.Sort method takes a one-dimensional array as an input and sorts the array elements in the ascending order.

The following code snippet creates an array of integers.

  int[] intArray = new int[] { 9, 2, 4, 3, 1, 5 };

The Array.Sort method takes array as an input and sorts the array in ascending order.

  Array.Sort(intArray);

To sort an array in descending order, we can use Sort.Reverse method. This method also takes an array as an input and sorts its elements in descending order. The following code snippet reverses an array.

  Array.Reverse(intArray);

Sort an Array of Int in C#

Here is the complete code that creates an array of integers and sorts in ascending and descending orders using Array.Sort and Array.Reverse methods.

static void Main(string[] args) {
    // Array of integers
    int[] intArray = new int[] {
        9,
        2,
        4,
        3,
        1,
        5
    };
    Console.WriteLine("Original array");
    foreach(int i in intArray) {
        Console.Write(i + " ");
    }
    Console.WriteLine();
    // Sort array in ASC order
    Console.WriteLine("Sorted array in ASC order");
    Array.Sort(intArray);
    foreach(int i in intArray) {
        Console.Write(i + " ");
    }
    Console.WriteLine();
    Console.WriteLine("Sorted array in DESC order");
    // Sort Array in DESC order
    Array.Reverse(intArray);
    foreach(int i in intArray) {
        Console.Write(i + " ");
    }
    Console.WriteLine();

The output of the above code is below where first it prints the original array, followed by the sorted array in ASC and DESC order respectively.


Sort an Array of Strings in C#

Now let’s sort an array of strings in C#. Sorting an array of strings is like sorting an array of int. The Array.Sort method takes an input value of an array of strings. The following code example shows how to sort an array of strings in ascending and descending orders using C#.

  // Array of strings
string[] strArray = new string[] { "Mahesh", "David", "Allen", "Joe", "Monica" };
Console.WriteLine();
Console.WriteLine("Original array");
foreach (string str in strArray)
{
    Console.Write(str + " ");
}
Console.WriteLine();
// Sort array
Array.Sort(strArray);
// Read array items using foreach loop
foreach (string str in strArray)
{
    Console.Write(str + " ");
}
Console.WriteLine();
Array.Reverse(strArray);
foreach (string str in strArray)
{
    Console.Write(str + " ");
}
Console.WriteLine();

The output of the above code displays original array, sorted array in the ascending order, and sorted array in the descending order.


Sort a Range of Elements In An Array

The Sort.Array method allows you to sort a range of elements within an array. For example, if an array has 11 elements but what if you want to sort only 1st to next 6 elements in the array? You can use that by passing the first starting index of the element followed by the number of elements to be sorted.

// Array of integers
int[] intArray = new int[] { 9, 2, 4, 3, 1, 5, 6, 9, 5, 7, 1, 0};
// Sort array from 1st element to 6th element. Skip 0th element.
Array.Sort(intArray, 1, 6);
foreach (int i in intArray)
{
    Console.Write(i + " ");
}

The output looks like the following where you can see only 6 elements are sorted after skipping the first element of the array.

9 1 2 3 4 5 6 9 5 7 1 0

Note that this sorting applies to all types of arrays not just integers.


0 comments:

Post a Comment

Topics

ADFS (1) ADO .Net (1) Ajax (1) Angular (43) Angular Js (15) ASP .Net (14) Authentication (4) Azure (3) Breeze.js (1) C# (47) CD (1) CI (2) CloudComputing (2) Coding (7) CQRS (1) CSS (2) Design_Pattern (6) DevOps (4) DI (3) Dotnet (8) DotnetCore (16) Entity Framework (2) ExpressJS (4) Html (4) IIS (1) Javascript (17) Jquery (8) Lamda (3) Linq (11) microservice (3) Mongodb (1) MVC (46) NodeJS (8) React (11) SDLC (1) Sql Server (32) SSIS (3) SSO (1) TypeScript (1) UI (1) UnitTest (1) WCF (14) Web Api (15) Web Service (1) XMl (1)

Dotnet Guru Archives