Letβs go through Lists, Dictionaries, and Sets in C# β key collection types in .NET that are more flexible than arrays.
π 1. List<T>
A List is a dynamic array β it can grow or shrink in size.
Key Points
-
Generic (
T
specifies the type of elements) -
Supports adding, removing, sorting, searching
-
Part of
System.Collections.Generic
Example
using System;
using System.Collections.Generic;
List<int> numbers = new List<int>();
numbers.Add(10);
numbers.Add(20);
numbers.Add(30);
Console.WriteLine(numbers[1]); // 20
numbers.Remove(20); // Remove element
Console.WriteLine(numbers.Count); // 2
// Iterating
foreach (int num in numbers)
Console.WriteLine(num);
Other Useful Methods
-
Insert(index, value)
β insert at specific position -
Sort()
β sort the list -
Contains(value)
β check if value exists -
Clear()
β remove all elements
π 2. Dictionary<K,V>
A Dictionary stores key-value pairs.
-
Generic types:
K
= key,V
= value -
Keys must be unique
-
Part of
System.Collections.Generic
Example
Dictionary<string, int> ages = new Dictionary<string, int>();
ages.Add("Alice", 25);
ages.Add("Bob", 30);
// Access by key
Console.WriteLine(ages["Alice"]); // 25
// Update value
ages["Alice"] = 26;
// Iterating
foreach (var kvp in ages)
Console.WriteLine($"{kvp.Key}: {kvp.Value}");
Other Useful Methods
-
ContainsKey(key)
β check if key exists -
Remove(key)
β remove a key-value pair -
Count
β number of entries
π 3. HashSet
A HashSet is an unordered collection of unique elements.
-
No duplicates allowed
-
Efficient for lookups
-
Part of
System.Collections.Generic
Example
HashSet<int> numbers = new HashSet<int>();
numbers.Add(1);
numbers.Add(2);
numbers.Add(2); // Ignored, already exists
Console.WriteLine(numbers.Count); // 2
// Check if exists
if (numbers.Contains(1))
Console.WriteLine("1 exists");
// Iterating
foreach (int num in numbers)
Console.WriteLine(num);
Other Useful Methods
-
Remove(value)
β remove element -
UnionWith(otherSet)
β combine sets -
IntersectWith(otherSet)
β common elements
π 4. Comparison Table
Collection | Type of Data | Key Feature | Example Use Case |
---|---|---|---|
List | Ordered list | Dynamic size, allows duplicates | Storing a list of names |
Dictionary<K,V> | Key-value pairs | Fast lookup by key | Storing user IDs and names |
HashSet | Unique elements | No duplicates, fast lookups | Unique tags, IDs, or items |
β Tips
-
List β use for ordered data where duplicates are allowed
-
Dictionary<K,V> β use for lookup by key
-
HashSet β use for unique elements and efficient membership checks