HashSet and Uniqueness
Track distinct values.
What Is a HashSet?
HashSet<T> stores a collection of unique values with no duplicates. Adding a value already present simply does nothing.
Like a dictionary, it is backed by a hash table, so membership tests are average O(1). It does not keep insertion order.
using System.Collections.Generic;
var seen = new HashSet<int>();
seen.Add(1);
seen.Add(1); // ignored, still one elementAdd Returns a Bool
Add returns true if the value was new and false if it was already present.
That return value is useful for detecting duplicates in one step, without a separate Contains check.
using System;
using System.Collections.Generic;
class Program {
static void Main() {
var set = new HashSet<string>();
Console.WriteLine(set.Add("a")); // True
Console.WriteLine(set.Add("a")); // False
}
}All lessons in this course
- List in Practice
- Dictionary Lookups
- HashSet and Uniqueness
- Choosing a Collection