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

CollectionType of DataKey FeatureExample Use Case
ListOrdered listDynamic size, allows duplicatesStoring a list of names
Dictionary<K,V>Key-value pairsFast lookup by keyStoring user IDs and names
HashSetUnique elementsNo duplicates, fast lookupsUnique tags, IDs, or items

βœ… Tips

  1. List β†’ use for ordered data where duplicates are allowed

  2. Dictionary<K,V> β†’ use for lookup by key

  3. HashSet β†’ use for unique elements and efficient membership checks