Limited Offer
60% OFF on all plans!

HashSet & SortedSet in C#

Work with unique collections using HashSet<T> and SortedSet<T>, perform union, intersection, difference, and understand set vs map internals.

Set Basics

1. Creating an Empty Set

`HashSet<T>` stores unique values with O(1) average add/lookup.

2. Creating a Set with Initial Values

Initialize a HashSet from a collection literal or existing list.

Basic Set Operations

1. Adding Values to a Set

`Add()` returns `true` if the value was new, `false` if it was a duplicate.

2. Checking if a Value Exists

`Contains()` returns `true` if the value is in the set — O(1).

3. Removing a Value

`Remove()` deletes the value and returns `true` if it existed.

4. Clearing the Set

`Clear()` empties the set — Count becomes 0.

5. Getting Set Size

`Count` returns the number of unique elements.

Traversing a Set

1. Traversing using foreach

Use `foreach` to iterate every element — order is not guaranteed.

2. Traversing using ForEach (lambda)

Convert to a List first, then use `.ForEach()` with a lambda.

Converting Set

1. Converting Set to List

Use `new List<T>(set)` or LINQ `.ToList()`.

2. Converting List to Set (Remove Duplicates)

Pass a list into `new HashSet<T>()` to deduplicate.

Set Operations

1. Union of Two Sets

`UnionWith()` adds all elements of another set into the current set.

2. Intersection of Two Sets

`IntersectWith()` keeps only elements present in both sets.

3. Difference of Two Sets

`ExceptWith()` removes all elements found in another set.

Set Variants

1. SortedSet (Sorted Order)

`SortedSet<T>` keeps elements in ascending order at all times.

2. ImmutableHashSet (Read-Only)

`ImmutableHashSet<T>` cannot be mutated after creation.

Set Fundamentals Using Dictionary

1. Simulating a Set Using Dictionary

A set is just a dictionary where only the keys matter.

2. Why HashSet Exists if Dictionary Can Do This?

`HashSet<T>` is more memory-efficient and has cleaner set-operation APIs.

3. Dictionary vs HashSet — Internals

Both `Dictionary<K,V>` and `HashSet<T>` use the same hash-table mechanism internally. A `HashSet<T>` is essentially a `Dictionary<T, _>` where the value slot is empty.