How to get a subset in a SortedSet in C#?

CsharpServer Side ProgrammingProgramming

To get a subset in 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);
      }
      SortedSet<string> set3 = set2.GetViewBetween("CD", "EF");
      Console.WriteLine("Elements in SortedSet3...");
      foreach (string res in set3){
         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
Elements in SortedSet3...
CD
DE
EF

Example

Let us now see another example −

 Live Demo

using System;
using System.Collections.Generic;
public class Demo {
   public static void Main(){
      SortedSet<int> set1 = new SortedSet<int>();
      set1.Add(50);
      set1.Add(100);
      set1.Add(150);
      set1.Add(200);
      set1.Add(250);
      set1.Add(300);
      set1.Add(350);
      set1.Add(400);
      set1.Add(450);
      set1.Add(500);
      Console.WriteLine("Elements in SortedSet1...");
      foreach (int res in set1){
         Console.WriteLine(res);
      }
      SortedSet<int> set2 = set1.GetViewBetween(150, 400);
      Console.WriteLine("Elements in SortedSet2...");
      foreach (int res in set2){
         Console.WriteLine(res);
      }
   }
}

Output

This will produce the following output −

Elements in SortedSet1...
50
100
150
200
250
300
350
400
450
500
Elements in SortedSet2...
150
200
250
300
350
400
raja
Published on 10-Dec-2019 11:19:37
Advertisements