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
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
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
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.
