C Sharp Sorted Set

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

C# SortedSet<T>

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.

C# SortedSet<T> example

Let's see an example of generic SortedSet class that stores elements using Add() method and iterates elements using for-each loop.

 
  1. using System;  
  2. using System.Collections.Generic;  
  3.   
  4. public class SortedSetExample  
  5. {  
  6.     public static void Main(string[] args)  
  7.     {  
  8.         // Create a set of strings  
  9.         var names = new SortedSet<string>();  
  10.         names.Add("Sonoo");  
  11.         names.Add("Ankit");  
  12.         names.Add("Peter");  
  13.         names.Add("Irfan");  
  14.         names.Add("Ankit");//will not be added  
  15.           
  16.         // Iterate SortedSet elements using foreach loop  
  17.         foreach (var name in names)  
  18.         {  
  19.             Console.WriteLine(name);  
  20.         }  
  21.     }  
  22. }  

Output:

Ankit
Irfan
Peter
Sonoo

C# SortedSet example 2

Let's see another example of generic SortedSet class that stores elements using Collection initializer.

 
  1. using System;  
  2. using System.Collections.Generic;  
  3.   
  4. public class SortedSetExample  
  5. {  
  6.     public static void Main(string[] args)  
  7.     {  
  8.         // Create a set of strings  
  9.         var names = new SortedSet<string>(){"Sonoo""Ankit""Peter""Irfan"};  
  10.           
  11.         // Iterate SortedSet elements using foreach loop  
  12.         foreach (var name in names)  
  13.         {  
  14.             Console.WriteLine(name);  
  15.         }  
  16.     }  
  17. }  

Output:

Ankit
Irfan
Peter
Sonoo