The C# SortedSet class is suitable for managing, deleting, or observing elements while keeping them in ascending order and preventing duplicates. If there is a need to store distinct elements in a sorted manner, it is recommended to utilize the SortedSet class, which is located within the System.Collections.Generic namespace.
C# SortedSet__PRESERVE_5__ example
Let's examine a basic SortedSet<T> class that stores elements utilizing the Add function and iterates through elements using a for-each loop.
Example
using System;
using System.Collections.Generic;
public class SortedSetExample
{
public static void Main(string[] args)
{
// Create a set of strings
var names = new SortedSet<string>();
names.Add("Sonoo");
names.Add("Ankit");
names.Add("Peter");
names.Add("Irfan");
names.Add("Ankit");//will not be added
// Iterate SortedSet elements using foreach loop
foreach (var name in names)
{
Console.WriteLine(name);
}
}
}
Output:
Output
Ankit
Irfan
Peter
Sonoo
C# SortedSet__PRESERVE_7__ example 2
Let's explore a different instance of a standard SortedSet<T> class that stores items through a Collection initializer.
Example
using System;
using System.Collections.Generic;
public class SortedSetExample
{
public static void Main(string[] args)
{
// Create a set of strings
var names = new SortedSet<string>(){"Sonoo", "Ankit", "Peter", "Irfan"};
// Iterate SortedSet elements using foreach loop
foreach (var name in names)
{
Console.WriteLine(name);
}
}
}
Output:
Output
Ankit
Irfan
Peter
Sonoo