When working with collections in C#, developers often come across HashSet<T>
and List<T>
. Both are powerful tools, but they serve different purposes. Understanding the key differences between them can help you write more efficient and readable code.
In this blog post, we’ll explore what makes HashSet
and List
different, when to use each, and how their performance compares in various scenarios
🔍 What is a List in C#?
A List<T>
is an ordered collection of elements that can contain duplicates. It works like a dynamic array, meaning its size can grow as you add more items.
Key Features:
-
Maintains the order of elements.
-
Allows duplicate values.
-
Provides index-based access (
list[0]
,list[1]
, etc.). -
Slower for
Contains()
checks in large lists (O(n) time).e.g.
List<int> numbers = new List<int> { 1, 2, 3, 3, 4 };
🔍 What is a HashSet in C#?
A HashSet<T>
is an unordered collection that contains only unique elements. It is implemented using a hash table, making it ideal for fast lookups.
Key Features:
-
Does not allow duplicates.
-
Unordered — no guarantee of item sequence.
-
Much faster lookups with O(1) average time for
Contains()
andAdd()
. -
Great for checking membership or removing duplicates.
e.g.
HashSet<int> numbers = new HashSet<int> { 1, 2, 3, 4 };numbers.Add(3); // Will be ignored as 3 already exists
🎥 Watch the Full Video
No comments:
Post a Comment