Efficiently Managing Unique and Sorted Collections in C# with the `SortedSet` Class
Learn how to use C#'s `SortedSet
Working with Sorted Sets in C#: The `SortedSet` Class
Introduction
The `SortedSet
Key Features of `SortedSet`
- Uniqueness: Only unique elements are stored. Attempting to add a duplicate element has no effect.
- Sorted Order: Elements are automatically kept sorted according to their natural ordering (or a custom comparer, if provided).
- Efficient Operations: `SortedSet
` offers efficient methods for adding, removing, searching, and iterating through elements. - Namespace: Located in `System.Collections.Generic`.
Example 1: Adding Elements and Iterating
This example shows how to create a `SortedSet`, add elements using the `Add()` method, and then iterate through the sorted elements.
Example 1: Adding and Iterating
using System;
using System.Collections.Generic;
public class SortedSetExample {
public static void Main(string[] args) {
var names = new SortedSet<string>();
names.Add("Sonoo");
names.Add("Ankit");
names.Add("Peter");
names.Add("Irfan");
names.Add("Ankit"); // Duplicate - will be ignored
foreach (var name in names) {
Console.WriteLine(name);
}
}
}
Output Example 1
Ankit
Irfan
Peter
Sonoo
Example 2: Using Collection Initializer
A more concise way to create and populate a `SortedSet` is using a collection initializer.
Example 2: Collection Initializer
using System;
using System.Collections.Generic;
public class SortedSetExample {
public static void Main(string[] args) {
var names = new SortedSet<string> { "Sonoo", "Ankit", "Peter", "Irfan" };
foreach (var name in names) {
Console.WriteLine(name);
}
}
}
Output Example 2
Ankit
Irfan
Peter
Sonoo
Conclusion
The `SortedSet