HashSet<T>
In this page:
HashSet<T>
HashSet<T> stores unique elements with no defined order and no duplicates, backed by a hash table for fast lookups. Adding an element that already exists is silently ignored — Add returns false in that case. It's ideal for membership tests and removing duplicates from data.
Note: Use HashSet<T> instead of List<T> when you only care about "does this exist?", not order or duplicates.
Example: HashSet<T>
using System;
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
HashSet<int> ids = new HashSet<int> { 1, 2, 3 };
bool added = ids.Add(2); // already exists
ids.Add(4);
Console.WriteLine(added);
Console.WriteLine(ids.Contains(3));
Console.WriteLine(ids.Count);
}
}
Login to try C/C++/Java/PHP code in the editor
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: