How do I work with collections like List, Dictionary, and Array

In C#, collections like List, Dictionary, and Array are widely used to store and manipulate groups of objects. Each collection type offers specific functionalities suitable for different scenarios.

Working with List

A List is a dynamically sized array that can hold objects of the same type. It allows you to add, remove, and access elements easily.

// Creating a List List<int> numbers = new List<int>(); numbers.Add(1); numbers.Add(2); numbers.Add(3); // Accessing elements int firstNumber = numbers[0]; // 1 numbers.RemoveAt(1); // Removes the number '2'

Working with Dictionary

A Dictionary stores key-value pairs and is ideal for fast lookups by a unique key.

// Creating a Dictionary Dictionary<string, int> ageDictionary = new Dictionary<string, int>(); ageDictionary.Add("John", 30); ageDictionary.Add("Jane", 25); // Accessing a value by key int johnsAge = ageDictionary["John"]; // 30

Working with Array

An Array is a fixed-size collection of elements of the same type, perfect for storing a predetermined number of items.

// Creating an Array int[] numbersArray = new int[3] {1, 2, 3}; // Accessing elements int secondElement = numbersArray[1]; // 2

C# collections List Dictionary Array programming data structures