C# SortedSet class can be used to store, remove or view elements. It maintains ascending order and does not store duplicate elements. It is suggested to use SortedSet class if you have to store unique elements and maintain ascending order. It is found in System.Collections.Generic namespace.
Let's see an example of generic SortedSet<T> class that stores elements using Add() method and iterates elements using for-each loop.
using System; using System.Collections.Generic; public class SortedSetExample { public static void Main(string[] args) { // Create a set of strings var names = new SortedSet(); 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:
Let's see another example of generic SortedSet<T> class that stores elements using Collection initializer.
using System; using System.Collections.Generic; public class SortedSetExample { public static void Main(string[] args) { // Create a set of strings var names = new SortedSet(){"Sonoo", "Ankit", "Peter", "Irfan"}; // Iterate SortedSet elements using foreach loop foreach (var name in names) { Console.WriteLine(name); } } }