The SortedSet<T> class in C# is part of the System.Collections.Generic namespace.
It provides a collection of unique elements that are sorted automatically in ascending order.
Unlike a HashSet<T>, which doesn’t guarantee any particular order, a SortedSet<T> always maintains elements in sorted order. This makes it a useful data structure when you need both uniqueness and sorting in a collection.
In this tutorial, we’ll cover:
1. Creating a SortedSet<T>
To create a SortedSet<T>, include the System.Collections.Generic namespace. T is the type parameter representing the type of elements in the sorted set, such as int, string, or a custom class.
using System; using System.Collections.Generic; class Program { static void Main() { // Create an empty sorted set of integers SortedSet<int> numbers = new SortedSet<int>(); // Create a sorted set of strings with initial values SortedSet<string> names = new SortedSet<string> { "Alice", "Charlie", "Bob" }; Console.WriteLine("Initial names in sorted set:"); foreach (string name in names) { Console.WriteLine(name); } } }
Output:
Initial names in sorted set: Alice Bob Charlie
In this example:
- SortedSet<int> numbers = new SortedSet<int>(); creates an empty sorted set of integers.
- SortedSet<string> names = new SortedSet<string> { “Alice”, “Charlie”, “Bob” }; initializes a sorted set of strings with values. The output shows that SortedSet automatically sorts the elements.
2. Adding Elements to a Sorted Set
You can add elements to a sorted set using the Add method. Since SortedSet<T> only stores unique elements, duplicate values are automatically ignored.
using System; using System.Collections.Generic; class Program { static void Main() { SortedSet<int> numbers = new SortedSet<int>(); // Adding elements numbers.Add(20); numbers.Add(10); numbers.Add(30); numbers.Add(20); // Duplicate, will not be added Console.WriteLine("Numbers in sorted set:"); foreach (int number in numbers) { Console.WriteLine(number); } } }
Output:
Numbers in sorted set: 10 20 30
In this example:
- Add(20) tries to add 20 twice, but only one instance is stored because SortedSet<T> does not allow duplicates. The elements are automatically sorted.
3. Removing Elements
You can remove elements from a sorted set using Remove or Clear.
using System; using System.Collections.Generic; class Program { static void Main() { SortedSet<int> numbers = new SortedSet<int> { 10, 20, 30, 40 }; // Remove a specific element numbers.Remove(20); // Clear all elements from the sorted set numbers.Clear(); Console.WriteLine("Numbers in sorted set after clearing:"); foreach (int number in numbers) { Console.WriteLine(number); // No output since the set is empty } } }
Output:
Numbers in sorted set after clearing:
In this example:
- Remove(20) removes the element 20.
- Clear() removes all elements from the sorted set.
4. Accessing Elements
You can access specific elements using methods like Min, Max, GetViewBetween, First, and Last.
using System; using System.Collections.Generic; class Program { static void Main() { SortedSet<int> numbers = new SortedSet<int> { 10, 20, 30, 40, 50 }; // Access the minimum and maximum elements Console.WriteLine("Minimum: " + numbers.Min); Console.WriteLine("Maximum: " + numbers.Max); // Get elements between a specific range SortedSet<int> range = numbers.GetViewBetween(20, 40); Console.WriteLine("Elements between 20 and 40:"); foreach (int number in range) { Console.WriteLine(number); } } }
Output:
Minimum: 10 Maximum: 50 Elements between 20 and 40: 20 30 40
In this example:
- numbers.Min returns the smallest element in the set.
- numbers.Max returns the largest element in the set.
- GetViewBetween(20, 40) retrieves a view of the elements between 20 and 40 (inclusive).
5. Commonly Used Methods
Here are some additional useful methods for working with SortedSet<T>:
- Count: Gets the number of elements in the sorted set.
- Contains: Checks if a specific element exists in the set.
- ToArray: Converts the sorted set to an array.
using System; using System.Collections.Generic; class Program { static void Main() { SortedSet<int> numbers = new SortedSet<int> { 10, 20, 30, 40, 50 }; // Count the elements Console.WriteLine("Count of elements: " + numbers.Count); // Check if an element exists in the set Console.WriteLine("Contains 30: " + numbers.Contains(30)); // Convert to array int[] array = numbers.ToArray(); Console.WriteLine("Array from sorted set:"); foreach (int number in array) { Console.WriteLine(number); } } }
Output:
Count of elements: 5 Contains 30: True Array from sorted set: 10 20 30 40 50
6. Performing Set Operations
The SortedSet<T> class supports set operations like union, intersection, and difference.
using System; using System.Collections.Generic; class Program { static void Main() { SortedSet<int> setA = new SortedSet<int> { 1, 2, 3, 4 }; SortedSet<int> setB = new SortedSet<int> { 3, 4, 5, 6 }; // Union of setA and setB setA.UnionWith(setB); Console.WriteLine("Union of setA and setB:"); foreach (int number in setA) { Console.WriteLine(number); } // Reset setA and setB setA = new SortedSet<int> { 1, 2, 3, 4 }; setB = new SortedSet<int> { 3, 4, 5, 6 }; // Intersection of setA and setB setA.IntersectWith(setB); Console.WriteLine("Intersection of setA and setB:"); foreach (int number in setA) { Console.WriteLine(number); } // Reset setA and setB setA = new SortedSet<int> { 1, 2, 3, 4 }; setB = new SortedSet<int> { 3, 4, 5, 6 }; // Difference of setA and setB (elements in setA but not in setB) setA.ExceptWith(setB); Console.WriteLine("Difference of setA and setB:"); foreach (int number in setA) { Console.WriteLine(number); } } }
Output:
Union of setA and setB: 1 2 3 4 5 6 Intersection of setA and setB: 3 4 Difference of setA and setB: 1 2
In this example:
- UnionWith(setB) adds elements from setB to setA, resulting in the union.
- IntersectWith(setB) retains only elements that exist in both sets.
- ExceptWith(setB) removes elements from setA that also exist in setB.
7. Iterating Through a SortedSet<T>
You can iterate through a SortedSet<T> using a foreach loop. Since SortedSet<T> automatically sorts elements, they are iterated in ascending order.
using System; using System.Collections.Generic; class Program { static void Main() { SortedSet<string> colors = new SortedSet<string> { "Red", "Green", "Blue" }; Console.WriteLine("Colors in sorted set:"); foreach (string color in colors) { Console.WriteLine(color); } } }
Output:
Colors in sorted set: Blue Green Red
In this example:
- The SortedSet<string> called colors automatically sorts elements alphabetically, so they are printed in ascending order.
Summary
In this tutorial, we covered the SortedSet<T> class in C# and demonstrated its features:
- Creating a SortedSet<T>: Initializing sorted sets with or without initial values.
- Adding Elements: Using Add to add unique items (duplicates are ignored).
- Removing Elements: Using Remove and Clear.
- Accessing Elements: Using Min, Max, GetViewBetween, First, and Last.
- Commonly Used Methods: Methods like Count, Contains, and ToArray.
- Performing Set Operations: Using UnionWith, IntersectWith, and ExceptWith.
- Iterating Through a SortedSet: Using foreach to iterate through all elements in ascending order.
SortedSet<T> is a versatile and efficient collection type in C# that combines uniqueness, automatic sorting, and useful set operations, making it ideal for tasks requiring sorted, unique data.