C# SortedSet

Introduction

The SortedSet<T> class in C# represents a collection of objects that are maintained in sorted order. It ensures that all elements are unique and automatically sorts them as they are added. The SortedSet<T> class is part of the System.Collections.Generic namespace and is useful for scenarios where you need a collection that keeps its elements in a specific order.

Key Features of SortedSet

  • Unique Elements: Ensures that all elements are unique.
  • Automatic Sorting: Maintains elements in sorted order.
  • Efficient Search Operations: Provides efficient search operations due to the sorted nature of the collection.
  • Set Operations: Supports set operations such as union, intersection, and difference.

Creating a SortedSet

Declaration and Initialization

You can declare and initialize a SortedSet<T> in several ways:

Example

using System;
using System.Collections.Generic;

namespace SortedSetExample
{
    class Program
    {
        static void Main(string[] args)
        {
            // Creating an empty SortedSet
            SortedSet<int> numbers = new SortedSet<int>();

            // Creating a SortedSet with initial elements
            SortedSet<string> fruits = new SortedSet<string> { "Banana", "Apple", "Cherry" };

            // Adding elements to the SortedSet
            numbers.Add(3);
            numbers.Add(1);
            numbers.Add(2);

            // Displaying elements (will be sorted automatically)
            Console.WriteLine("Numbers: " + string.Join(", ", numbers));
            Console.WriteLine("Fruits: " + string.Join(", ", fruits));
        }
    }
}

Output

Numbers: 1, 2, 3
Fruits: Apple, Banana, Cherry

Common Operations on SortedSet

Adding Elements

  • Add: Adds an element to the SortedSet. Returns true if the element is successfully added; false if the element is already present.
bool isAdded = numbers.Add(4); // true
bool isDuplicateAdded = numbers.Add(2); // false

Removing Elements

  • Remove: Removes the specified element from the SortedSet. Returns true if the element is successfully removed; false otherwise.
bool isRemoved = numbers.Remove(2); // true
  • RemoveWhere: Removes all elements that match the conditions defined by the specified predicate.
numbers.RemoveWhere(n => n > 3);
  • Clear: Removes all elements from the SortedSet.
numbers.Clear();

Accessing Elements

  • Contains: Checks if the SortedSet contains the specified element. Returns true if the element is found; false otherwise.
bool hasApple = fruits.Contains("Apple"); // true

Iterating Through a SortedSet

You can iterate through a SortedSet using a foreach loop.

Example

foreach (int number in numbers)
{
    Console.WriteLine(number);
}

foreach (string fruit in fruits)
{
    Console.WriteLine(fruit);
}

Set Operations

  • UnionWith: Modifies the current SortedSet to contain all elements that are present in either the current SortedSet or the specified collection.
SortedSet<int> otherNumbers = new SortedSet<int> { 3, 4, 5 };
numbers.UnionWith(otherNumbers);
  • IntersectWith: Modifies the current SortedSet to contain only elements that are present in both the current SortedSet and the specified collection.
numbers.IntersectWith(otherNumbers);
  • ExceptWith: Removes all elements in the specified collection from the current SortedSet.
numbers.ExceptWith(otherNumbers);
  • SymmetricExceptWith: Modifies the current SortedSet to contain only elements that are present in either the current SortedSet or the specified collection, but not both.
numbers.SymmetricExceptWith(otherNumbers);

Practical Example

Let’s create a practical example where we use a SortedSet<T> to manage a collection of student names in sorted order.

Example

using System;
using System.Collections.Generic;

namespace StudentSortedSetExample
{
    class Program
    {
        static void Main(string[] args)
        {
            SortedSet<string> studentNames = new SortedSet<string> { "John Doe", "Jane Smith", "Sam Brown" };

            // Adding new student names
            studentNames.Add("Alice Johnson");
            studentNames.Add("Bob Lee");

            // Attempting to add a duplicate student name
            bool isAdded = studentNames.Add("John Doe"); // false

            // Removing a student name
            studentNames.Remove("Jane Smith");

            // Displaying all student names
            Console.WriteLine("Student Names:");
            foreach (string name in studentNames)
            {
                Console.WriteLine(name);
            }

            // Checking if a student name exists
            bool hasStudentName = studentNames.Contains("Sam Brown"); // true
            Console.WriteLine("Contains student name 'Sam Brown': " + hasStudentName);
        }
    }
}

Output

Student Names:
Alice Johnson
Bob Lee
John Doe
Sam Brown
Contains student name 'Sam Brown': True

Conclusion

The SortedSet<T> class in C# provides a collection of unique elements that are maintained in sorted order. It is ideal for scenarios where you need a collection that keeps its elements in a specific order and supports set operations efficiently. Understanding how to use SortedSet<T> effectively can help you manage collections of ordered data in your applications.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top