In this article [Show more]
SortedSet in C# with Example
In C#, the SortedSet<T> class provides an efficient way to maintain a collection of unique elements in sorted order. As part of the System.Collections.Generic namespace, this collection is valuable in scenarios requiring both sorted and unique elements. This article explores the key features of SortedSet<T>, practical applications, and examples of its use.
Key Features of SortedSet<T>
- Sorted Order: Elements are automatically sorted based on their natural ordering or a custom comparer.
- Unique Elements: Only unique elements are allowed, with duplicates ignored.
- Efficient Lookups: Provides fast lookups and set operations such as union, intersection, and difference.
Common Operations
- Add(T item): Adds an item to the set if it isn't already present.
- Remove(T item): Removes an item from the set.
- Contains(T item): Checks if an item exists in the set.
- Min/Max: Retrieves the smallest or largest item in the set.
Example: Using SortedSet<T> in C#
Here is a practical example demonstrating how to use SortedSet<T>:
using System;
using System.Collections.Generic;
public class SortedSetExample
{
public static void Main()
{
// Create a SortedSet of integers
SortedSet<int> numbers = new SortedSet<int> { 10, 20, 30, 40 };
// Adding a new number
numbers.Add(25);
// Attempt to add a duplicate
bool isAdded = numbers.Add(30);
Console.WriteLine("Was 30 added? " + isAdded); // Outputs: False
// Display the sorted set
Console.WriteLine("SortedSet contents:");
foreach (int number in numbers)
{
Console.WriteLine(number);
}
// Checking if an element exists
Console.WriteLine("Contains 25? " + numbers.Contains(25)); // True
// Retrieve the smallest and largest elements
Console.WriteLine("Min: " + numbers.Min); // 10
Console.WriteLine("Max: " + numbers.Max); // 40
// Remove an element
numbers.Remove(20);
Console.WriteLine("After removing 20:");
foreach (int number in numbers)
{
Console.WriteLine(number);
}
}
}
Practical Applications of SortedSet
- Sorted Data Processing: Ensures that elements are always sorted when retrieving or processing data.
- Ranking Systems: Use sorted sets for ranking algorithms where data must be stored and retrieved in sorted order.
- Set Operations: Perform fast and accurate set operations like union and intersection.
Conclusion
SortedSet<T> in C# is a versatile collection that combines the strengths of sorted ordering and uniqueness. By leveraging its features, developers can efficiently manage collections that require both attributes while maintaining fast lookups and accurate results.