C#
HashSet<T>
Learn unique-element collections with HashSet<T>.
HashSet<T>
HashSet<T> is a collection of unique elements. If you try to add the same value twice, the second add is ignored; only one copy remains.
The Add method returns a bool: true if the element was actually added, false if it was already present. Example: HashSet<int> set = new HashSet<int>(); set.Add(5);. Order is not guaranteed; the collection cannot be indexed.
Set operations
HashSet<T> supports classic set operations: UnionWith merges with another set, IntersectWith takes the intersection, ExceptWith takes the difference. These methods modify the current set in place.
Because the set is unordered, items cannot be accessed by index. You can iterate with foreach and quickly check an item's presence with Contains.
Exercise Unique cities
Declare HashSet<string> cities = new HashSet<string>();. Add the values "Ankara", "İzmir" and "Ankara" in order with Add (the third must be a duplicate). Then print cities.Count with Console.WriteLine.
Show example solution
Declare with HashSet<string> cities = new HashSet<string>();, call cities.Add("..."); three times (third is a duplicate), then print with Console.WriteLine(cities.Count);.
Example solution:
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// Add 3 cities (one duplicate) and print the unique count
HashSet<string> cities = new HashSet<string>();
cities.Add("Ankara");
cities.Add("İzmir");
cities.Add("Ankara");
Console.WriteLine(cities.Count);
}
}
Test yourself
-
HashSet Add
HashSet<int> set = new HashSet<int>();
____
Console.WriteLine(set.Count);
Show answer
HashSet<int> set = new HashSet<int>();
set.Add(5);
Console.WriteLine(set.Count);
-
Match each expression to its meaning
- HashSet<int>
- Unique integers
- set.Add(5)
- Tries to add
- set.Count
- Unique count
- set.Contains(5)
- Contains check
-
What does set.Count print after two Add calls?
HashSet<int> set = new HashSet<int>();
set.Add(5);
set.Add(5);
Console.WriteLine(set.Count);
Show answer
1 — Correct. The second Add is ignored; a single 5 remains, Count is 1.
Next lesson: Summary - Collections