Updated on

A SortedSet in C# is a data structure that stores unique elements and keeps them in sorted order, whatever order we add them in. It also hands us its smallest and largest element, a live view of any range, and the classic set operations such as union and intersection.

Let’s create one and try its methods, then look at the benefits and drawbacks of using this data structure.

To download the source code for this article, you can visit our GitHub repository.

What Is a SortedSet in C#?

A SortedSet<T> in C# is a collection of unique elements that it keeps in sorted order. Each Add() puts the new element in its place, so a foreach loop always returns the elements from the smallest to the largest.

The order comes from a comparer. Without one, the set uses Comparer<T>.Default, which sorts numbers by value and strings by the rules of the current culture. For any other order, we pass our own IComparer<T> to the constructor.

The same comparer decides what counts as a duplicate. When Add() meets an element that compares as equal to one already in the set, it returns false and leaves the set as it was.

Under the hood, the set is a red-black tree, a binary search tree that keeps itself balanced. That is why adding, removing and finding an element all cost O(log n), and why the set can give us its smallest and largest element, or every element between two values, without sorting anything first.

The SortedSet<T> class has been available since .NET Framework 4.0 as part of the System.Collections.Generic namespace.

One notable feature of the SortedSet is its ability to efficiently perform set operations such as union, intersection, and difference, which makes it particularly useful for tasks such as creating a list of unique elements from multiple sets.

SortedSet does not permit duplicate elements. Trying to add a duplicate element will not affect the set. It does accept one null element when T is a reference type, though, and sorts it before every other element.

How to Create a SortedSet in C#?

For most of our examples, we intend to use a SortedSet that contains strings of some of the programming languages used today.

Let’s start by creating an empty SortedSet:

var languages = new SortedSet<string>();

SortedSet Constructor Overloads

We can use these overloads when working with the SortedSet class in C#:

OverloadDescription
SortedSet<T>()Creates an empty set that sorts with the default comparer for T.
SortedSet<T>(IComparer<T>)Creates an empty set that sorts with the comparer we pass.
SortedSet<T>(IEnumerable<T>)Creates a set from the elements of an existing collection, sorted with the default comparer and without duplicates.
SortedSet<T>(IEnumerable<T>, IComparer<T>)Creates a set from the elements of an existing collection, sorted with the comparer we pass and without duplicates.

To make our article as simple as possible, we are going to implement the first overload, SortedSet() and learn how it works. 

Add Items to a SortedSet

Let’s add a set of programming languages into a SortedSet<string> object, in a method of a public SortedSetMethods class:

public SortedSet<string> ProgrammingLanguages() 
{ 
    var languages = new SortedSet<string>(); 

    languages.Add("C"); 
    languages.Add("C++"); 
    languages.Add("C#"); 
    languages.Add("Java"); 
    languages.Add("Scala"); 
    languages.Add("TypeScript"); 
    languages.Add("Python"); 
    languages.Add("JavaScript"); 
    languages.Add("Rust");
    
    return languages;
}

Here, we insert elements into the languages SortedSet by invoking the Add() method.

In some cases, we may want to initialize a  SortedSet directly with values:

var languages = new SortedSet<string> { "C", "C++", "C#", "Java" };

Let’s initialize our SortedSet in the test constructor:

private readonly SortedSetMethods _sortedSet; 
private readonly SortedSet<string> _languages;

public SortedSetInCSharpUnitTests()
{
    _sortedSet = new SortedSetMethods();
    _languages = _sortedSet.ProgrammingLanguages();
}

Next, we can verify that our SortedSet has nine elements and check whether it contains one of the elements (“Java”) and the first element is (“C”):

Assert.IsInstanceOfType(_languages, typeof(SortedSet<string>));
Assert.AreEqual(9, _languages.Count);
Assert.IsTrue(_languages.Contains("Java"));
Assert.AreEqual("C", _languages.First());

We can successfully prove that _languages is of type SortedSet<string>. We use the Count property to check the number of elements in our SortedSet.

Also, we use the inbuilt Contains() method to check if the SortedSet has a specific element. The method takes the element as a parameter and returns a boolean value indicating whether or not the element is present in the set.

This technique can be helpful for quickly checking if an element exists in the SortedSet without iterating through all of the elements.

Add Duplicate Elements in a SortedSet in C#

A SortedSet does not allow adding duplicate elements. It will not affect the set if we try to add a duplicate element. Before it inserts an element, it compares it with the elements already in the set, and when it finds an equal one, it leaves the set alone.

Let’s attempt to add duplicate elements to the _languages SortedSet:

_languages.Add("C");
_languages.Add("C++");
_languages.Add("C#");

Assert.IsInstanceOfType(_languages, typeof(SortedSet<string>));
Assert.AreEqual(9, _languages.Count);

When we try to add duplicate values to _languages, its values will not change, as the set already contains those values. Therefore, its count remains nine instead of twelve.

Add() also tells us whether it added anything:

Assert.IsFalse(_languages.Add("Java"));
Assert.IsTrue(_languages.Add("Go"));

It returns false for “Java”, which is already in the set, and true for “Go”, which is new.

How Does a SortedSet Deal With Object Sorting?

A SortedSet<T> sorts objects with the IComparer<T> in its Comparer property. We set it once, through the constructor, and the set uses it for every insert, lookup and removal.

When we don’t pass a comparer, the set takes Comparer<T>.Default. For our programming languages, that is the default string comparer, which is why they come out in alphabetical order. For a type of our own, the default comparer needs the type to implement IComparable<T> or IComparable. Without either, adding the second element throws an ArgumentException.

The comparer is also the set’s only equality check. SortedSet<T> doesn’t call Equals() or GetHashCode(), so two objects that the comparer ranks the same are duplicates, even when all their other properties differ, and the set keeps only the first.

So a comparer for a sorted set has to compare enough properties to tell any two different elements apart.

If IComparer<T> is new to us, our article on IComparable vs IComparer explains the interface. Let’s see what the comparer rule means with a tuple of a language name and the year the language first appeared, sorted by year:

var byYear = Comparer<(string Name, int Year)>.Create(
    (x, y) => x.Year.CompareTo(y.Year));

var languages = new SortedSet<(string Name, int Year)>(byYear)
{
    ("Python", 1991), ("Java", 1995), ("C", 1972), ("JavaScript", 1995)
};

Assert.AreEqual(3, languages.Count);
Assert.AreEqual(("C", 1972), languages.Min);
Assert.IsFalse(languages.Any(l => l.Name == "JavaScript"));

Java and JavaScript both first appeared in 1995, so our comparer calls them equal. The set keeps Java, which we added first, and JavaScript is gone. Add() did return false for it, but a collection initializer throws that result away, so nothing warns us.

The fix is to break the tie with a second property:

var byYearThenName = Comparer<(string Name, int Year)>.Create(
    (x, y) => x.Year != y.Year
        ? x.Year.CompareTo(y.Year)
        : string.CompareOrdinal(x.Name, y.Name));

var languages = new SortedSet<(string Name, int Year)>(byYearThenName)
{
    ("Python", 1991), ("Java", 1995), ("C", 1972), ("JavaScript", 1995)
};

Assert.AreEqual(4, languages.Count);
Assert.AreEqual(("JavaScript", 1995), languages.Max);

Now all four languages stay, and inside 1995 the names decide the order. Comparer<T>.Create() is one of several ways to build a comparer in .NET.

One more rule follows from the comparer: the values it compares must not change while the element sits in the set. Microsoft Learn warns that “changing the sort values of existing items is not supported and may lead to unexpected behavior.” When we changed the sort key of one element from 5 to 100 in a set of three, the set went on to list its keys as 1, 100, 9.

Iterate Through a SortedSet in C#

We can iterate through a SortedSet object by using a foreach loop statement.

Let’s invoke the languages SortedSet in our main program and iterate through it:

var sortedSet = new SortedSetMethods();
var programmingLanguages = sortedSet.ProgrammingLanguages();

Console.WriteLine("The SortedSet Contains these elements:");

foreach (var language in programmingLanguages) 
{
    Console.WriteLine(language);
}

After executing the program, we can see that our programming languages are in the correct alphabetic order:

The SortedSet Contains these elements:
C
C#
C++
Java
JavaScript
Python
Rust
Scala
TypeScript

Remove All Elements From a SortedSet in C#

What if we want to remove all the elements in a SortedSet? We can make use of the Clear() inbuilt method.

Let’s verify that the Clear() method removes all elements from the _languages set:

_languages.Clear();

Assert.AreEqual(0, _languages.Count);
Assert.IsNull(_languages.FirstOrDefault());

After invoking the Clear() method, we can prove that we removed all the elements from the _languages set as it has a count of zero.  

Copy SortedSet Elements to an Array

The CopyTo() method copies a part of or the entire SortedSet into a one-dimensional array of the same type. The method has some overloads, which give us an option of copying elements at the beginning of the destination array or from a specific index.

To keep our example simple, let’s copy all the elements in the _languages SortedSet into an array by taking advantage of the CopyTo() method:

var languagesArray = new string[9];

_languages.CopyTo(languagesArray);

Assert.AreEqual(9, languagesArray.Length);
Assert.AreEqual("C", languagesArray[0]);
Assert.AreEqual("TypeScript", languagesArray[8]);
Assert.IsNotNull(languagesArray);

Alternatively, we can convert a SortedSet into an array by invoking the ToArray() method:

var languagesArray = _languages.ToArray();

Perform Set Difference Between Two SortedSets in C#

This operation performs a set difference operation between two sets. If we perform a set difference between sets A and B, the operation returns the elements in A that are not present in B.

Let’s understand this concept with another example:

var moreLanguages = new SortedSet<string> { "C", "C++", "C#", "Java", "Scala", "Assembly", 
                    "Pascal", "HTML", "CSS", "PHP" };

_languages.ExceptWith(moreLanguages);

Assert.AreEqual(4, _languages.Count);
Assert.IsTrue(_languages.Contains("TypeScript"));
Assert.IsTrue(_languages.Contains("Python"));
Assert.IsTrue(_languages.Contains("JavaScript"));
Assert.IsTrue(_languages.Contains("Rust"));
Assert.IsFalse(_languages.Contains("Assembly"));

The ExceptWith() method keeps only the elements that are in _languages but not in moreLanguages, which are: “TypeScript”, “Python”, “JavaScript” and “Rust”. 

Find Common Elements Between Two SortedSets

An intersection between sets A and B entails finding the common elements. To accomplish such an operation in C#, we use the inbuilt IntersectWith() method. 

Let’s understand how to perform an intersection operation with an example:

var moreLanguages = new SortedSet<string> { "C", "C++", "C#", "Java", "Scala", "Assembly", 
                    "Pascal", "HTML", "CSS", "PHP" };

_languages.IntersectWith(moreLanguages);

Assert.AreEqual(5, _languages.Count);
Assert.IsTrue(_languages.Contains("C"));
Assert.IsTrue(_languages.Contains("C++"));
Assert.IsTrue(_languages.Contains("C#"));
Assert.IsTrue(_languages.Contains("Java"));
Assert.IsTrue(_languages.Contains("Scala"));
Assert.IsFalse(_languages.Contains("Assembly"));

Here, the IntersectWith() method modifies the _languages SortedSet by retaining the elements that are common in both _languages and moreLanguages sets. 

How to Check A SortedSet Is a Subset of Another

When we want to check whether a SortedSet instance is a proper subset of another SortedSet instance, we use the IsProperSubsetOf() method. Likewise, we can use the IsProperSupersetOf() method to determine if a SortedSet is a proper superset of another SortedSet.

Let’s put this theory into practice:

var moreLanguages = new SortedSet<string> {"C", "C++", "C#", "Java", "Scala", "TypeScript", 
                    "Python", "JavaScript", "Rust", "Assembly", "Pascal"};

Assert.IsTrue(_languages.IsSubsetOf(moreLanguages));
Assert.IsTrue(_languages.IsProperSubsetOf(moreLanguages));
Assert.IsTrue(moreLanguages.IsSupersetOf(_languages));
Assert.IsTrue(moreLanguages.IsProperSupersetOf(_languages));

We create a larger set moreLanguages that contains more elements, including all the elements in the _languages set. Therefore, _languages is a proper subset of moreLanguages and the latter is the proper superset of the former. 

So, what’s the difference between a proper subset and a normal one? 

In set theory, a subset is a collection of elements within another set. A proper subset, also known as a strictly smaller subset, is a subset that contains strictly fewer elements than the larger set. 
A proper subset will always have fewer elements than the larger set, which may not be true for a subset. For example, if we have the set A = {1, 2, 3}, B = {1, 2} is a proper subset because it contains strictly fewer elements than A. On the other hand, C = {1, 2, 3} would not be considered a proper subset because it has the same number of elements as A.

Determine Whether Two SortedSets Overlap

In some situations, we may want to check whether two SortedSet objects share common elements without evaluating whether they are equal. That’s where we can take advantage of the Overlaps() method to achieve our objective:

var commonLanguages = new SortedSet<string> { "C", "C++", "C#", "Java", "Scala", "TypeScript", 
                      "Python", "JavaScript", "Rust", "Assembly", "Pascal" };
var differentLanguages = new SortedSet<string> { "Assembly", "Pascal", "HTML", "CSS", "PHP" };

Assert.IsTrue(commonLanguages.Overlaps(_languages));
Assert.IsTrue(differentLanguages.Overlaps(commonLanguages));
Assert.IsFalse(differentLanguages.Overlaps(_languages));

We can see that the commonLanguages and _languages SortedSets have common elements. The same case applies to differentLanguages and commonLanguages. However, differentLanguages and _languages do not have overlapping elements. 

Remove a Particular Element From a SortedSet

To remove an item from the SortedSet, we can use the Remove() method. Like the Add() method, it takes the object as a parameter and removes it from the SortedSet.

Let’s put our knowledge into practice with one more method in the SortedSetMethods class:

public SortedSet<string> RemoveElement(SortedSet<string> sortedSet, string valueToRemove) 
{
    sortedSet.Remove(valueToRemove);

    return sortedSet;
}

Here, the RemoveElement() method takes a SortedSet<string> and a string as parameters and uses the Remove() method to remove an element before returning the updated SortedSet. 

Next, we can verify that our new method successfully removes elements:

var elementToRemove = "Java";

var updatedLanguages = _sortedSet.RemoveElement(_languages, elementToRemove);

Assert.IsFalse(updatedLanguages.Contains(elementToRemove));
Assert.AreEqual(8, _languages.Count);

We invoke the RemoveElement() method and pass our SortedSet, and a string (“Java”), which we can prove is removed as the updated SortedSet does not contain that value, and its count decreases by one. 

Remove Elements From a SortedSet Through Predicates

Besides using the inbuilt Remove() method, we can use the RemoveWhere() method that takes a predicate as a parameter to set conditions that determine whether we remove an element. To illustrate this concept, let’s modify our _languages SortedSet to remove programming languages that start with a specific character:

_languages.RemoveWhere(element => element.StartsWith("C"));
Assert.IsFalse(_languages.Contains("C"));
Assert.IsFalse(_languages.Contains("C++"));
Assert.IsFalse(_languages.Contains("C#"));

We can verify that the RemoveWhere() method removes all elements starting with the letter ‘C.’

Reverse Elements of a SortedSet in C#

In some cases, we may want to reverse the order of the elements we have in a SortedSet. We can take advantage of the inbuilt Reverse() method to achieve our goal. The method returns an IEnumerable<T> object, which iterates over the SortedSet in reverse order. 

Let’s illustrate how the Reverse() method works:

var reversedSet = _languages.Reverse();
var firstElement = reversedSet.First();
var lastElement = reversedSet.Last();

Assert.IsInstanceOfType(reversedSet, typeof(IEnumerable<string>));
Assert.AreEqual("TypeScript", firstElement);
Assert.AreEqual("C", lastElement);

We can prove that we get an IEnumerable<string> object, which iterates over the _languages SortedSet in reverse order. 

How to Get the Min, Max and a Range of a SortedSet?

A sorted set always knows where its smallest and largest elements are. The Min and Max properties return them, so we don’t need LINQ’s First() and Last():

Assert.AreEqual("C", _languages.Min);
Assert.AreEqual("TypeScript", _languages.Max);

On an empty set, Min and Max don’t throw. They return the default value of T, which is null for strings, but 0 for a SortedSet<int>, a value we can easily mistake for a real element.

When we need every element between two values, we call GetViewBetween(). It takes the lowest and the highest value we want, and it includes both ends:

var view = _languages.GetViewBetween("C", "Java");

CollectionAssert.AreEqual(new[] { "C", "C#", "C++", "Java" }, view.ToArray());

_languages.Add("Go");
view.Add("F#");

CollectionAssert.AreEqual(new[] { "C", "C#", "C++", "F#", "Go", "Java" }, view.ToArray());
Assert.IsTrue(_languages.Contains("F#"));
Assert.ThrowsExactly<ArgumentOutOfRangeException>(() => view.Add("Rust"));

The view is not a copy. Microsoft Learn says the method “provides a window into the underlying SortedSet<T> itself”, and the test shows what that means. “Go”, which we add to _languages, appears in the view. “F#”, which we add to the view, lands in _languages. And adding “Rust” through the view throws an ArgumentOutOfRangeException, because “Rust” falls outside the range from “C” to “Java”.

If we need a snapshot that doesn’t change, we copy the view with ToArray() or pass it to the constructor of a new SortedSet<T>.

How to Check if Two SortedSets Are Equal in C#

In some cases, we may want to compare whether the current SortedSet and another collection contain the same elements. We can use the SetEquals() method to achieve our goal:

var moreLanguages = new SortedSet<string> { "Assembly", "Pascal", "HTML", "CSS", "PHP" };
var sameLanguagesInAList = new List<string>
{
    "Rust", "Java", "C", "C#", "C++", "Scala", "TypeScript", "Python", "JavaScript", "Java"
};

Assert.IsFalse(_languages.SetEquals(moreLanguages));
Assert.IsTrue(_languages.SetEquals(sameLanguagesInAList));

The moreLanguages object is not equal to the _languages object, so we expect the SetEquals() operation to return false.

The list holds the same nine languages in a different order, with “Java” twice, and SetEquals() still returns true.

Note this method ignores the order of elements and any duplicates in the other collection compared to the current SortedSet. 

Store Unique Elements From Two SortedSets

Sometimes, we may want to modify a SortedSet to store unique elements between two sets. That’s where the SymmetricExceptWith() method comes into play, as we can use it to accomplish our purpose.

Let’s look at using the SymmetricExceptWith() method:

var moreLanguages = new SortedSet<string> { "Assembly", "Pascal", "HTML", "CSS", "PHP" };

_languages.SymmetricExceptWith(moreLanguages);

Assert.AreEqual(14, _languages.Count);

The SymmetricExceptWith() method modifies the _languages SortedSet to make it have unique elements from both itself and moreLanguages SortedSet. Therefore, since both sets have unique values, the modified _languages SortedSet now contains fourteen elements. 

How to Search for an Element in a SortedSet in C#

Besides using the inbuilt Contains() method to check whether a SortedSet contains a specific value, we can use the inbuilt TryGetValue (T equalValue, out T actualValue) technique to achieve the same result. The method takes two parameters, the first being the value to search for and the next being what the search finds or the default value when the search doesn’t yield any results. 

Let’s put this theory into practice:

Assert.IsTrue(_languages.TryGetValue("C#", out var found));
Assert.AreEqual("C#", found);
Assert.IsTrue(_languages.Contains("C#"));
Assert.IsFalse(_languages.TryGetValue("Assembly", out _));
Assert.IsFalse(_languages.Contains("Assembly"));

Here, _languages contains “C#” and does not contain “Assembly”. TryGetValue() returns the element the set stores in its out parameter, found, and in the second call we use the discard _ because we don’t need that value.

That stored element is the reason to pick TryGetValue() over Contains(). With a custom comparer, the value we search with and the value in the set can be different objects that only compare as equal. With our year comparer from earlier, searching for ("Ruby", 1995) returns ("Java", 1995).

Perform a Union Between Two SortedSets

When we want to join two sets, we perform a union operation. For example, when we want to perform a union between two sets, A and B, we copy the elements in set B over into set A. 

Let’s perform a UnionWith() operation between _languages and moreLanguages SortedSet to illustrate this concept:

var moreLanguages = new SortedSet<string> { "Assembly", "Pascal", "HTML", "CSS", "PHP" };

_languages.UnionWith(moreLanguages);
Assert.AreEqual(14, _languages.Count);

The UnionWith() method copies the elements in moreLanguages SortedSet into the _languages SortedSet hence, the latter now has fourteen elements instead of nine. 

Benefits of Using a SortedSet in C#

First, SortedSet objects facilitate quick insertion and retrieval operations, as adding, removing and finding an element take O(log n) time, and the set stays sorted after every change.

Also, we can use the SortedSet class in applications that do not allow duplicate elements, which helps us eliminate data redundancy.

A SortedSet can quickly check if an element is present in the set without iterating through all elements and returns elements in a specific order. 

Overall, a SortedSet in C# can significantly aid in managing and manipulating sorted collections of unique elements.

Drawbacks of Using a SortedSet in C#

Using the SortedSet may not be suitable for all situations where we need to store duplicate elements.

Additionally, the performance benefits of using a SortedSet may not be significant in small collections.

And when we don’t need the order at all, a HashSet<T> finds an element in constant time instead of O(log n). We measure the two side by side in HashSet vs SortedSet.

A SortedSet<T> is also not meant for several threads changing it at once. Microsoft Learn points to ImmutableSortedSet<T> as the thread-safe alternative, and we cover it with the other immutable collections.

In some cases, accessing and manipulating elements by their index may also be necessary rather than simply iterating through them in sorted order. Another collection type, such as a list, may be more appropriate in such cases.

Overall, it is crucial to carefully evaluate whether the restrictions and advantages of using a SortedSet are suitable for a given situation before implementing it in C# code.

SortedSets vs SortedLists

One similarity between a SortedSet and a SortedList in C# is that both data structures maintain their elements in sorted order. However, a SortedList<TKey, TValue> stores key-value pairs. It rejects duplicate keys, just like a SortedSet rejects duplicate elements, but its values may repeat. In addition, a SortedSet has faster insertion and removal times than a SortedList, as the latter internally uses an array structure, which requires shifting elements around during insertion and removal. Adding a key in the middle of a SortedList costs O(n), while a SortedSet adds any element in O(log n).

So, when we only need sorted unique values with nothing attached to them, the SortedSet is the simpler and faster choice.

Conclusion

SortedSet in C# provides a valuable tool for managing and manipulating sorted collections of unique elements. However, it is essential to carefully consider whether its restrictions and advantages make it suitable for a specific situation before implementing it in code. If you enjoyed this article, feel free to check out our article on a similar topic, HashSet in C#.

In short, we reach for a SortedSet<T> when we need unique elements in order, the smallest or largest of them, or every element between two values, and we give it a comparer that can tell any two of our elements apart.

Tested with .NET 10.0.10 and MSTest 4.5.2.