Efficiently Managing Unique and Sorted Collections in C# with the `SortedSet` Class

Learn how to use C#'s `SortedSet` class to create and manage collections of unique elements that are automatically kept in sorted order. This tutorial demonstrates key methods, provides code examples, and highlights the benefits of using `SortedSet` for various data handling tasks requiring both uniqueness and sorted order.



Working with Sorted Sets in C#: The `SortedSet` Class

Introduction

The `SortedSet` class in C# provides a way to store a collection of unique elements, automatically keeping them sorted in ascending order. This is particularly useful when you need to maintain uniqueness and order simultaneously.

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` class offers a clean and efficient solution for managing unique, sorted collections in C#. Its simplicity and performance make it a valuable tool for various programming tasks.