A HashSet helps you keep a collection of items where each item appears only once. It automatically ignores duplicates.
HashSet for unique elements in C Sharp (C#)
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Syntax
C Sharp (C#)
HashSet<T> set = new HashSet<T>(); // Add items set.Add(item); // Check if item exists bool hasItem = set.Contains(item); // Remove item set.Remove(item);
T is the type of items you want to store, like int or string.
HashSet does not keep items in order.
Examples
C Sharp (C#)
HashSet<string> fruits = new HashSet<string>(); fruits.Add("apple"); fruits.Add("banana"); fruits.Add("apple"); // duplicate ignored
C Sharp (C#)
HashSet<int> numbers = new HashSet<int>() { 1, 2, 3, 2 }; // The set will contain 1, 2, 3 only once each
C Sharp (C#)
if (fruits.Contains("banana")) { Console.WriteLine("Banana is in the set."); }
Sample Program
This program creates a HashSet of colors, adds some colors including a duplicate, and shows how duplicates are ignored. It also checks if a color exists and removes one.
C Sharp (C#)
using System; using System.Collections.Generic; class Program { static void Main() { HashSet<string> colors = new HashSet<string>(); colors.Add("red"); colors.Add("blue"); colors.Add("green"); colors.Add("red"); // duplicate ignored Console.WriteLine("Colors in the set:"); foreach (var color in colors) { Console.WriteLine(color); } Console.WriteLine($"Contains 'blue'? {colors.Contains("blue")}"); colors.Remove("green"); Console.WriteLine("After removing 'green':"); foreach (var color in colors) { Console.WriteLine(color); } } }
Important Notes
HashSet is very fast for checking if an item exists.
Order of items in HashSet is not guaranteed.
Use HashSet when you want only unique items without caring about order.
Summary
HashSet stores unique items and ignores duplicates automatically.
It is useful for fast lookups and removing duplicates.
Items in a HashSet are not stored in any particular order.
Practice
1. What is the main purpose of using a
HashSet<T> in C#?easy
Solution
Step 1: Understand HashSet behavior
A HashSet automatically ignores duplicate entries and stores only unique elements.Step 2: Compare with other collections
Unlike lists or dictionaries, HashSet does not allow duplicates and does not maintain order.Final Answer:
To store unique elements without duplicates -> Option CQuick Check:
HashSet = Unique elements [OK]
Hint: HashSet always keeps unique items only [OK]
Common Mistakes:
- Thinking HashSet keeps elements sorted
- Assuming HashSet allows duplicates
- Confusing HashSet with Dictionary
2. Which of the following is the correct way to declare and initialize a
HashSet<int> with values 1, 2, and 3?easy
Solution
Step 1: Check HashSet initialization syntax
HashSet can be initialized with collection initializer syntax using curly braces after the constructor.Step 2: Validate each option
var set = new HashSet<int> {1, 2, 3}; uses correct syntax: new HashSet<int> {1, 2, 3}; Options A, B, and C have invalid syntax.Final Answer:
var set = new HashSet<int> {1, 2, 3}; -> Option BQuick Check:
Use curly braces after constructor for initialization [OK]
Hint: Use curly braces after new HashSet for values [OK]
Common Mistakes:
- Using parentheses with multiple values directly
- Trying to declare array instead of HashSet
- Incorrect assignment syntax
3. What will be the output of the following C# code?
var set = new HashSet<string>();
set.Add("apple");
set.Add("banana");
set.Add("apple");
Console.WriteLine(set.Count);medium
Solution
Step 1: Add elements to HashSet
"apple" is added first, then "banana", then "apple" again.Step 2: Understand duplicate handling
The second "apple" is ignored because HashSet stores unique elements only.Final Answer:
2 -> Option DQuick Check:
Duplicates ignored, count = 2 [OK]
Hint: Count equals unique items added, duplicates ignored [OK]
Common Mistakes:
- Counting duplicates as separate elements
- Assuming HashSet allows duplicates
- Confusing Count with number of Add calls
4. Identify the error in this code snippet using
HashSet<int>:HashSet<int> numbers = new HashSet<int>(); numbers.Add(1); numbers.Add(2); numbers.Add(1); Console.WriteLine(numbers[0]);
medium
Solution
Step 1: Review HashSet usage
HashSet stores unique elements but does not support accessing elements by index.Step 2: Identify invalid operation
Using numbers[0] causes a compile-time error because HashSet has no indexer.Final Answer:
HashSet does not support indexing with [] -> Option AQuick Check:
No index access on HashSet [OK]
Hint: HashSet has no indexer; use foreach or Contains [OK]
Common Mistakes:
- Trying to access elements by index
- Thinking Add returns a value
- Assuming duplicates cause errors
5. You have a list of integers with duplicates:
Which code snippet correctly creates a
List<int> nums = new List<int> {1, 2, 2, 3, 4, 4, 4, 5};Which code snippet correctly creates a
HashSet<int> containing only the unique elements from nums?hard
Solution
Step 1: Understand HashSet constructor
HashSet has a constructor that accepts an IEnumerable<T> to initialize with unique elements.Step 2: Analyze each option
var unique = new HashSet<int>(nums); correctly passes the list to the constructor. var unique = new HashSet<int>(); unique.Add(nums); tries to add the whole list as one item (invalid). var unique = new HashSet<int>(); foreach(var n in nums) unique = n; assigns int to HashSet variable (invalid). var unique = new HashSet<int>(); unique.AddRange(nums); uses AddRange which HashSet does not have.Final Answer:
var unique = new HashSet<int>(nums); -> Option AQuick Check:
Use constructor with collection for unique set [OK]
Hint: Pass list to HashSet constructor for unique items [OK]
Common Mistakes:
- Using Add to add whole list at once
- Trying to assign int to HashSet variable
- Using AddRange which HashSet lacks
