.Net

C# Arrays and collections – Part 1

Introduction

In the world of programming, as our apps become more sophisticated and handle larger amounts of information, it’s crucial to manage that data effectively. Enter data structures; they help us store and retrieve data faster, making our programs run smoothly. In a nutshell, data structures provide efficiency, reusability, and abstraction.

Difference between Array and Collection

In simple termes, an array is a group of same things. It only holds one type of item (strongly typed) and has a set size. On the other hand, a collection is a bit more flexible, it can hold a mix of things, and it can change in size. However if we want to make sure our collection follows rules and only contains one type of thing, we can use “Generic.” this helps us to keep things organised and follow a set type.

Purpose of the article

I aim to clarify the concept of arrays and collections in C# for both novice and intermediate programmers. I will explore the fundamentals of arrays, demonstrating their efficient organisation and storage of data. Additionally, I’ll delve into collections, highlighting their dynamic nature and the importance of generics in maintaining type consistency.

By the end of this article, you will gain a clear understanding of how to use arrays and collections in C# and grasp how these foundational data structures contribute to writing efficient and well-organised code.

Arrays in C#

One-dimensional array
Declaration and initialisation 

The process of declaring and initialising arrays offers flexibility. In this paragraph we will see together the difference approches to declare and initialise arrays.

Inline Initialisation

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

This method allows you to declare and initialise an array in a single line, you can use it when you know the values at the time of declaration.

Using “new” Keyword

int[] numbers = new int[5];

The ‘new’ keyword is used to create an array, specifying its size. In this case, elements are initialized with default values (e.g., 0 for integers). This method is useful when you need to create an array of a specific size without immediately knowing the values

Separate declaration and initialization

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

This approche can be useful when you want to declare the array first and initialise it later. for example when you want to fill the array with user input.

In the end, the choice of which method to use depends on the specific requirements of our code. Understanding these different approaches will empower us to make informed decisions based on our needs.

Array Elements

Elements are organised in sequential order, starting from index 0 for the first element, and the total number of elements in an array is determinate bu its size. Indexing is the process of referring to an element within the array using its position.

Example : in this example we have an array of names ( 4 elements of type string ) and we can see the index of each element.

Accessing Elements

Accessing elements involves retrieving or modifying the value stored at a specific index. Elements can be accessed using square brackets with the desired index.

Example : Retrieving an element from the array using index

Example : modifying an element of array using index

If we intend yo subtract the name of ‘Edouard’ stored at index 2 with ‘Xavier’, we can use the following command :

names[2] = "Xavier";

The updated state of the array will be

Caution: Ensure the index used falls within the array bounds to avoid runtime error. For example, if we consider our array of names, attempting to retrieve an element using index 4 or 5 is invalid since the bounds of our array are restricted to values between 0 and 3.

Search in array using value

To search for a value in an array, you can use ‘Array.IndexOf’ method

string[] names = { "Mohammed", "David", "Xavier", "Jayden" };

string searchName = "Xavier";
int index = Array.IndexOf(names, searchName);

if (index != -1)
{
  Console.WriteLine(searchName + " found at index " + index);
}
else
{
  Console.WriteLine(searchName + " not found in the array");
}
Iterate through each element of an array
string[] names = { "Mohammed", "David", "Xavier", "Jayden" };

Console.WriteLine("Accessing all elements in the array using a loop:");
for (int i = 0; i < names.Length; i++)
{
  Console.WriteLine("Element at index " + i + ": " + names[i]);
}

In this example, the ‘for’ loop is used to iterate through each element of the array. The loop starts from index 0 and continues until ‘i’ is less than the length of the array.

Multi-dimensional array

In C#, a multi-dimensional array is an array with more than one dimension, The most common types are two-dimensional arrays, but you can have arrays more dimensions as well.

Example of a 2D array of names

Declaration and initialisation, the first index represents the row, and the second index represents the column :

Accessing elements in the 2D array :

for (int row = 0; row < namesMatrix.GetLength(0); row++)
{
     for (int col = 0; col < namesMatrix.GetLength(1); col++)
     {
       Console.WriteLine("Element at row " + row + ", col " + col + ": " + namesMatrix[row, col]);
    }
}

Similar to single-dimensional arrays, you can employ separate initialisation with multi-dimensional arrays :

string[,] namesMatrix2 = new string[3, 4];
namesMatrix2[0, 0] = "Mohammed";
namesMatrix2[0, 1] = "David";
namesMatrix2[0, 2] = "Xavier";
namesMatrix2[0, 3] = "Jayden";
namesMatrix2[1, 0] = "Sophia";
namesMatrix2[1, 1] = "Emma";
namesMatrix2[1, 2] = "Olivia";
namesMatrix2[1, 3] = "Biden";
namesMatrix2[2, 0] = "Anas";
namesMatrix2[2, 1] = "Khadija";
namesMatrix2[2, 2] = "Noel";
namesMatrix2[2, 3] = "Ben";
Jagged Array

A jagged array is an array of arrays. The primary distinction between a jagged array and a regular array lies in the fact that, each element can have varying lengths. This characteristic impacts a higher degree of flexibility to jagged arrays.

Example : In a real-life scenario. A jagged array can efficiently represent students and their courses.

 // Jagged array representing students and their courses
 string[][] studentCourses = new string[3][];
        
// Student 1: Enrolled in 2 courses
studentCourses[0] = new string[] { "Mathematics", "Physics" };

// Student 2: Enrolled in 3 courses
studentCourses[1] = new string[] { "History", "English", "Biology" };

// Student 3: Enrolled in 1 course
studentCourses[2] = new string[] { "Computer Science" };

Example : Accessing elements in the jagged array :

for (int i = 0; i < studentCourses.Length; i++)       {         Console.Write("Student " + (i + 1) + " Courses: ");
 for (int j = 0; j < studentCourses[i].Length; j++)
     {
         Console.Write(studentCourses[i][j] + ", ");
     }

 Console.WriteLine();
}

Array operations

Sort the elements of an array

int[] numbers = { 5, 2, 8, 1, 3 };
Array.Sort(numbers);
// Now, numbers will be { 1, 2, 3, 5, 8 }

Reverses the order of the elements in an array

char[] characters = { 'a', 'b', 'c', 'd' };
Array.Reverse(characters);
// Now, characters will be { 'd', 'c', 'b', 'a' }

Copy elements from one array to another

int[] sourceArray = { 1, 2, 3, 4, 5 };
int[] destinationArray = new int[5];
Array.Copy(sourceArray, destinationArray, 5);
// Now, destinationArray will be { 1, 2, 3, 4, 5 }

Return the index of the first occurence of a specified value in an array

string[] names = { "Mohammed", "Xavier", "Edouard", "David" };
int index = Array.IndexOf(names, "Xavier");
// index will be 1

Determine whether any element of the array satisfies a specified condition

int[] numbers = { 1, 2, 3, 4, 5 };
bool hasEvenNumber = Array.Exists(numbers, x => x % 2 == 0);
// hasEvenNumber will be true

Convert each element in the array to a different type

string[] stringNumbers = { "1", "2", "3", "4", "5" };
int[] intNumbers = Array.ConvertAll(stringNumbers, int.Parse);
// intNumbers will be { 1, 2, 3, 4, 5 }

Use LINQ for querying operations

int[] numbers = { 1, 2, 3, 4, 5 };
var evenNumbers = numbers.Where(n => n % 2 == 0);
// evenNumbers will be { 2, 4 }

The end

Thank you for reading. We look forward to welcoming you in Part 2 of this article, where we will delve into topic of collections.

What's your reaction?

Excited
0
Happy
0
In Love
0
Not Sure
0
Silly
0
MBensaid
Hello, I'm Mohammed, a passionate developer. I share my enthusiasm and knowledge on MBenSaid to inspire fellow enthusiasts. Together, let's build a bright digital future!

    Leave a reply

    Your email address will not be published. Required fields are marked *

    Next Article:

    0 %