How do you remove duplicates from a collection using HashSet<T>?
Short answer: Add all elements from the collection to a HashSet<T>, which automatically removes duplicates. List<int> numbers = new List<int> { 1, 2, 2, 3, 3, 4 }; HashSet<int> uniqueNumbers = new HashSet<int>(numbers); Now, uniqueNumbers contains only unique values: {1, 2, 3, 4}.
Example code
Add all elements from the collection to a HashSet<T>, which automatically removes duplicates. List<int> numbers = new List<int> { 1, 2, 2, 3, 3, 4 };
HashSet<int> uniqueNumbers = new HashSet<int>(numbers); Now, uniqueNumbers contains only unique values: {1, 2, 3, 4}.
Real-world example (ShopNest)
When applying a coupon, ShopNest keeps used coupon codes in a HashSet<string> so “already used?” checks stay fast and unique.
Say this in the interview
- Define — one clear sentence (the short answer above).
- Example — relate it to a project like ShopNest or your real work.
- Trade-off — when you would not use it.
Share this Q&A
Share preview image: https://www.toolliyo.com/images/toolliyo-logo.png