VOOZH about

URL: https://www.geeksforgeeks.org/c-sharp/sortedset-in-c-sharp/

⇱ SortedSet in C# - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

SortedSet in C#

Last Updated : 23 Apr, 2026

SortedSet<T> is a collection of unique elements that are automatically sorted in ascending order by default. It is implemented using a balanced binary search tree (red-black tree), which provides efficient insertion, deletion and search operations. There are some key features mentioned below:

  • Automatically stores elements without duplicates in sorted order.
  • Supports mathematical operations such as UnionWith, IntersectWith and ExceptWith.
  • Add, Remove and Contains operations have O(log n) time complexity.

Creating a SortedSet

Step 1: Include System.Collections.Generic namespace

using System.Collections.Generic;

Step 2: Create a SortedSet using the SortedSet Class

SortedSet<type_of_sortedset> sortedset_name = new SortedSet<type_of_sortedset>();

Example:


Output
SortedSet elements:
1 2 4 6 7 8 

Note: Duplicate elements are automatically ignored.

Performing Different Operations on SortedSet

1. Adding Element

  • Add(): We can use the Add method to put elements in the sorted set
  • Collection-Initializer: Using the collection initializer we can directly put the element with initialization.

// Using the Add() method
SortedSet<int> num= new SortedSet<int>();
num.Add(1);
num.Add(2);

// Using Collection Initalizer
SortedSet<int> num = new SortedSet<int> { 2, 1, 4,3 };

2. Accessing Elements

Using foreach loop: We can use foreach loop to iterate each element to access the sorted set.

SortedSet<int> numbers= new SortedSet<int> { 2,3,4,5};

foreach (int num in numbers)

Console.WriteLine(num);

Using ForEach loop with Lambda Expressions: Lambda expressions reduces the number of code lines and enhances the code readability.

SortedSet<int> numbers = new SortedSet<int> { 2, 3, 4, 5 };

numbers.ToList().ForEach(n => Console.WriteLine(n));

Using ElementAt() with LINQ: The SortedSet does not directly support indexing but we can use LINQ and use ElementAt() method.

using System.Linq;


SortedSet<int> numbers= new SortedSet<int> { 2,3,4,5 };
Console.WriteLine(numbers.ElementAt(0));

Example: Accessing Elements Using Different Methods


Output
Accessing using foreach loop:
2 3 4 5 
Accessing using ForEach loop:
1 2 3 

3. Removing Elements

SortedSet<T> provides three ways to remove elements:

Example:


Output
Total number of elements present in set: 4
Total number of elements present in set after Remove(1): 3
Total number of elements present in set after Clear(): 0

4. Check If an Element Exists

We can check the presence of a specific element using the Contains method. Example:


Output
Element is available.
Comment

Explore