How to create a SortedSet in C#?


To create a SortedSet, the code is as follows −

Example

 Live Demo

using System;
using System.Collections.Generic;
public class Demo {
   public static void Main(){
      SortedSet<string> set1 = new SortedSet<string>();
      set1.Add("AB");
      set1.Add("BC");
      set1.Add("CD");
      set1.Add("EF");
      Console.WriteLine("Elements in SortedSet1...");
      foreach (string res in set1){
         Console.WriteLine(res);
      }
      SortedSet<string> set2 = new SortedSet<string>();
      set2.Add("BC");
      set2.Add("CD");
      set2.Add("DE");
      set2.Add("EF");
      set2.Add("AB");
      set2.Add("HI");
      set2.Add("JK");
      Console.WriteLine("Elements in SortedSet2 (Enumerator for SortedSet)...");
      SortedSet<string>.Enumerator demoEnum = set2.GetEnumerator();
      while (demoEnum.MoveNext()) {
         string res = demoEnum.Current;
         Console.WriteLine(res);
      }
   }
}

Output

This will produce the following output −

Elements in SortedSet1...
AB
BC
CD
EF
Elements in SortedSet2 (Enumerator for SortedSet)...
AB
BC
CD
DE
EF
HI
JK

Example

Let us now see another example −

 Live Demo

using System;
using System.Collections.Generic;
public class Demo {
   private static bool demo(int i){
      return ((i % 10) == 0);
   }
   public static void Main(String[] args){
      SortedSet<int> set1 = new SortedSet<int>();
      set1.Add(200);
      set1.Add(215);
      set1.Add(310);
      set1.Add(500);
      set1.Add(600);
      Console.WriteLine("SortedSet elements...");
      foreach (int i in set1){
         Console.WriteLine(i);
      }
      Console.WriteLine(" ");
      set1.RemoveWhere(demo);
      Console.WriteLine("SortedSet after removing some elements...");
      foreach (int i in set1){
         Console.WriteLine(i);
      }
   }
}

Output

This will produce the following output −

SortedSet elements...
200
215
310
500
600
SortedSet after removing some elements...
215

Updated on: 06-Dec-2019

52 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements