Collections in C#: List, Dictionary, and HashSet


Collections are essential in C# for storing and manipulating groups of data. In this guide, you'll explore three common collection types in C#: List, Dictionary, and HashSet. These collections serve different purposes and have unique characteristics.


List<T>


The `List` is a dynamic array that can store elements of a specific type. It provides flexibility for adding, removing, and accessing elements in a list.


Example of using a `List`:


using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
List<int> numbers = new List<int>();
// Adding elements
numbers.Add(1);
numbers.Add(2);
numbers.Add(3);
// Accessing elements
int firstNumber = numbers[0]; // 1
int lastNumber = numbers[numbers.Count - 1]; // 3
// Removing elements
numbers.Remove(2); // Removes the value 2 from the list
// Iterating through the list
foreach (int number in numbers)
{
Console.WriteLine(number);
}
}
}

Dictionary<TKey, TValue>


The `Dictionary` is a key-value pair collection where each element is associated with a unique key. It's useful for fast lookups based on the key.


Example of using a `Dictionary`:


using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
Dictionary<string, int> ages = new Dictionary<string, int>();
// Adding key-value pairs
ages["Alice"] = 30;
ages["Bob"] = 25;
// Accessing values by key
int aliceAge = ages["Alice"]; // 30
// Checking for key existence
bool hasKey = ages.ContainsKey("Bob"); // true
// Iterating through key-value pairs
foreach (var kvp in ages)
{
Console.WriteLine($"Name: {kvp.Key}, Age: {kvp.Value}");
}
}
}

HashSet<T>


The `HashSet` is an unordered collection of unique elements. It's suitable for tasks that require checking for duplicate values.


Example of using a `HashSet`:


using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
HashSet<string> colors = new HashSet<string>();
// Adding elements
colors.Add("Red");
colors.Add("Green");
colors.Add("Blue");
// Adding a duplicate (ignored)
colors.Add("Red");
// Checking for element existence
bool hasGreen = colors.Contains("Green"); // true
bool hasYellow = colors.Contains("Yellow"); // false
// Iterating through elements
foreach (string color in colors)
{
Console.WriteLine(color);
}
}
}

Conclusion


Collections play a vital role in C# programming, and you've explored three essential collection types: List, Dictionary, and HashSet. Each collection serves distinct purposes and provides unique capabilities to help you manage and manipulate data effectively.


Practice using these collections in your C# programs to become proficient in data manipulation. As you continue your programming journey, you'll discover more advanced collection types and scenarios for their usage.