Curriculum
SortedSet is a class in C# that represents a collection of unique elements, sorted in ascending order. It is similar to HashSet, but the elements are ordered based on their natural ordering or a custom IComparer implementation. Here’s an example of using SortedSet to store and manipulate a collection of integers:
using System;
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
// Create a SortedSet of integers
SortedSet<int> numbers = new SortedSet<int>();
// Add some numbers to the set
numbers.Add(3);
numbers.Add(2);
numbers.Add(1);
// Display the contents of the set
Console.WriteLine("Numbers in set:");
foreach (int number in numbers)
{
Console.WriteLine(number);
}
// Remove a number from the set
numbers.Remove(2);
// Display the updated contents of the set
Console.WriteLine("Numbers in set after removing 2:");
foreach (int number in numbers)
{
Console.WriteLine(number);
}
}
}
In this example, we first create an empty SortedSet<int> object called numbers. We then add some integers to the set using the Add method. We use a foreach loop to display the contents of the set.
Next, we use the Remove method to remove the number 2 from the set. Finally, we use another foreach loop to display the updated contents of the set.
Here are some other useful methods provided by the SortedSet class:
Count: Returns the number of elements in the set.Contains: Determines whether an element is in the set.UnionWith: Modifies the current set to include all elements from another collection.IntersectWith: Modifies the current set to contain only elements that are also in another collection.Clear: Removes all elements from the set.Here’s an example that demonstrates some of these methods:
// Create two sorted sets of integers
SortedSet<int> set1 = new SortedSet<int> { 1, 2, 3 };
SortedSet<int> set2 = new SortedSet<int> { 3, 4, 5 };
// Combine the two sets
set1.UnionWith(set2);
// Display the contents of the combined set
Console.WriteLine("Combined set:");
foreach (int number in set1)
{
Console.WriteLine(number);
}
// Remove all elements that are not in both sets
set1.IntersectWith(set2);
// Display the contents of the intersected set
Console.WriteLine("Intersected set:");
foreach (int number in set1)
{
Console.WriteLine(number);
}
It’s important to note that SortedSet provides many other useful properties and methods for working with sets, such as SymmetricExceptWith to modify the current set to contain only elements that are not also in another collection, IsSubsetOf to determine whether the current set is a subset of another collection, and GetEnumerator to get an enumerator that iterates through the set. Additionally, the SortedSet class provides constructors that allow you to specify a custom IComparer implementation for ordering the elements.