In C#, an array is a collection of elements that are of the same type, stored in contiguous memory locations.

More about Array in C#

What is Array in C#

Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value. C# arrays are zero-based, meaning the first element has an index of 0, the second element has an index of 1, and so on.

Key Characteristics of Arrays in C#:

  1. Fixed Size: Once an array is created, its size cannot be changed. You must specify the number of elements the array will hold when you create it.
  2. Same Type: All elements in an array must be of the same type. This type is specified when you declare the array.
  3. Indexed Access: Elements in an array can be accessed using their index. Indexing starts at 0.
  4. Memory Efficiency: Arrays are stored in contiguous memory locations, which can make accessing elements faster compared to some other collection types.

In the following exercise, the return value should be: "Blazor, Blender, C-Sharp, Django, Figma, Godot, MAUI, Python, Unity."

Here is the task to accomplish:

  • Sort the table (Array) alphabetically.
  • Construct the character string.
  • Add the necessary commas and periods.
  • Return the requested character string.
using System;
 
namespace Coding.Exercise
{
    public class SortArrayAscending
    {
        public static string CourseList()
        {
            string[] courses = {"Unity", "Blender", "Godot", "Figma", "C-Sharp", "Blazor", "MAUI", "Python", "Django"};
            
            // Array.Reverse(courses);  // Reverse the sorted array to get the desired order
            
            // Sort the array alphabetically
            Array.Sort(courses);

            // Append a period to the last item
            courses[courses.Length - 1] += ".";

            // Join the array elements into a single string
            string result = String.Join(", ", courses);
            
            // Retourner la chaîne de caractère demandée
            return result;
        }
    }
}

 

BONUS - More about Array

Below are several examples showcasing different ways to work with arrays in C#:

1. Basic Array Declaration and Initialization

using System;

public class BasicArrayExample
{
    public static void Main(string[] args)
    {
        // Declare and initialize an array of integers
        int[] numbers = { 1, 2, 3, 4, 5 };

        // Access elements by index
        Console.WriteLine("First element: " + numbers[0]); // Output: 1
        Console.WriteLine("Third element: " + numbers[2]); // Output: 3

        // Modify an element
        numbers[1] = 20;
        Console.WriteLine("Modified second element: " + numbers[1]); // Output: 20
    }
}

 

RESULT:

2. Iterating Over an Array

  • Iterating over an array means going through each element of the array one by one, usually to perform some operation on each element, such as printing the elements, modifying them, or calculating a sum. In C#, there are several ways to iterate over an array: using a for loop, a foreach loop, or LINQ (Language Integrated Query).
using System;

public class IteratingArrayExample
{
    public static void Main(string[] args)
    {
        string[] fruits = { "Apple", "Banana", "Cherry", "Date" };

        // Using a for loop
        for (int i = 0; i < fruits.Length; i++)
        {
            Console.WriteLine(fruits[i]);
        }

        Console.WriteLine("**********");

        // Using a foreach loop
        foreach (string fruit in fruits)
        {
            Console.WriteLine(fruit);
        }

        Console.WriteLine("**********");

        // Convert array to list and use ForEach to iterate
        fruits.ToList().ForEach(fruit => Console.WriteLine(fruit));
        
        Console.WriteLine("**********");
        
        // Use LINQ Select to project each element and iterate using foreach
        var fruitQuery = fruits.Select(fruit => fruit);

        foreach (var fruit in fruitQuery)
        {
            Console.WriteLine(fruit);
        }        
    }
}

 

RESULT:

3. Array Methods

  • Arrays in C# come with various built-in methods that allow you to manipulate and query the array.
using System;

public class ArrayMethodsExample
{
    public static void Main(string[] args)
    {
        int[] numbers = { 5, 3, 8, 1, 2 };

        // Sorting the array
        Array.Sort(numbers);
        Console.WriteLine("Sorted array: " + string.Join(", ", numbers)); // Output: 1, 2, 3, 5, 8

        // Reversing the array
        Array.Reverse(numbers);
        Console.WriteLine("Reversed array: " + string.Join(", ", numbers)); // Output: 8, 5, 3, 2, 1

        // Finding the index of an element
        int index = Array.IndexOf(numbers, 3);
        Console.WriteLine("Index of 3: " + index); // Output: 2

        // Copying the array
        int[] copiedArray = new int[numbers.Length];
        Array.Copy(numbers, copiedArray, numbers.Length);
        Console.WriteLine("Copied array: " + string.Join(", ", copiedArray)); // Output: 8, 5, 3, 2, 1
    }
}

 

RESULT:

4. Multidimensional Arrays

  • C# supports multidimensional arrays, including two-dimensional and three-dimensional arrays.
using System;

public class MultidimensionalArrayExample
{
    public static void Main(string[] args)
    {
        // Declare and initialize a 2D array
        int[,] matrix = {
            { 1, 2, 3 },
            { 4, 5, 6 },
            { 7, 8, 9 }
        };

        // Access elements by row and column indices
        Console.WriteLine("Element at (0,0): " + matrix[0, 0]); // Output: 1
        Console.WriteLine("Element at (1,2): " + matrix[1, 2]); // Output: 6

        // Iterate over the 2D array
        for (int i = 0; i < matrix.GetLength(0); i++)
        {
            for (int j = 0; j < matrix.GetLength(1); j++)
            {
                Console.Write(matrix[i, j] + " ");
            }
            Console.WriteLine();
        }
    }
}

 

RESULT:

5. Jagged Arrays

  • Jagged arrays are arrays of arrays, where each "inner" array can have different lengths. Jagged arrays (arrays of arrays) also require nested loops, but the lengths of the inner arrays can differ.
using System;

public class JaggedArrayExample
{
    public static void Main(string[] args)
    {
        // Declare and initialize a jagged array
        int[][] jaggedArray = new int[3][];
        jaggedArray[0] = new int[] { 1, 2 };
        jaggedArray[1] = new int[] { 3, 4, 5 };
        jaggedArray[2] = new int[] { 6, 7, 8, 9 };

        // Access elements
        Console.WriteLine("Element at [0][1]: " + jaggedArray[0][1]); // Output: 2
        Console.WriteLine("Element at [2][3]: " + jaggedArray[2][3]); // Output: 9

        // Iterate over the jagged array
        foreach (int[] array in jaggedArray)
        {
            foreach (int element in array)
            {
                Console.Write(element + " ");
            }
            Console.WriteLine();
        }
    }
}

 

RESULT:

6. Working with Arrays and LINQ

  • LINQ provides a way to perform operations on arrays in a more declarative manner. You can use methods like Select, Where, and Aggregate to iterate over and manipulate arrays.
using System;
using System.Linq;

public class LinqArrayExample
{
    public static void Main(string[] args)
    {
        int[] numbers = { 1, 2, 3, 4, 5 };

        // Use LINQ to filter and sort the array
        var evenNumbers = numbers.Where(n => n % 2 == 0).OrderBy(n => n);

        Console.WriteLine("Even numbers: " + string.Join(", ", evenNumbers)); // Output: 2, 4

        // Use LINQ to find the sum and average
        int sum = numbers.Sum();
        double average = numbers.Average();

        Console.WriteLine("Sum: " + sum);       // Output: 15
        Console.WriteLine("Average: " + average); // Output: 3
    }
}

 

RESULT:

Yardley Estiverne
Yardley Estiverne
AI MVP & Software Developer | AI Tech Entrepreneur

AI MVP Developer - Blazor, C# .NET Developer with good crafted hands-on experience in developing and deploying robust web solutions. Proficient in .NET programming and its associated libraries, with understanding of SQL practices. I also create backend application using Django Rest Framework.

LinkedIn:Yardley

No comments