Arrays and Collections

Arrays and collections in C# provide ways to group and manipulate sets of variables. They are essential when dealing with multiple similar data items. In this section, we'll explore arrays and some of the most common collection types in C#.

Arrays

An array is a data structure that allows you to store multiple variables of the same type in a single data structure. Here's an example of how to declare and initialize an array in C#:

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

In this example, numbers is an array of integers. It is initialized with five elements. Arrays are zero-indexed in C#, which means the first element is at position 0:

csharpCopy codeint firstNumber = numbers[0];  // firstNumber is 1

You can also modify the contents of an array:

csharpCopy codenumbers[0] = 10;  // The first element is now 10

Collections

While arrays are useful, they have limitations. They can't grow or shrink in size after they're created, and they don't provide built-in methods for common tasks like sorting or searching. Collections in C# provide more flexibility and functionality. Here are some of the most common collection types:

List

The List<T> class is a generic collection that can be resized dynamically. It also provides methods for adding, removing, and searching items:

List<int> numbers = new List<int> {1, 2, 3, 4, 5};
numbers.Add(6);  // The list now contains 1, 2, 3, 4, 5, 6
numbers.Remove(1);  // The list now contains 2, 3, 4, 5, 6

Dictionary

The Dictionary<TKey, TValue> class is a collection of keys and values. It allows you to access values quickly based on a unique key:

Dictionary<string, int> ages = new Dictionary<string, int> {
    {"Alice", 30},
    {"Bob", 35}
};

int aliceAge = ages["Alice"];  // aliceAge is 30

HashSet

The HashSet<T> class is a collection of unique elements. It is often used to remove duplicates from a collection or to test membership of an item:

HashSet<int> uniqueNumbers = new HashSet<int> {1, 2, 2, 3, 3, 3};
// uniqueNumbers now contains 1, 2, 3

Reference: https://www.tutorialsteacher.com/csharp/csharp-collection

Complete and Continue