C# | How to create a SortedSet

SortedSet class represents the collection of objects in sorted order. This class comes under the System.Collections.Generic namespace.

Properties :

  • In 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.

Syntax:

SortedSet<T> mySortedSet = new SortedSet<T>();

Here, mySortedSet is the name of the SortedSet and T is Type Parameter.

Below given are some examples to understand the implementation in a better way:

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# code to create a SortedSet
using System;
using System.Collections.Generic;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
  
        // Creating a SortedSet of integers
        SortedSet<int> mySortedSet = new SortedSet<int>();
  
        // Adding elements in mySortedSet
        for (int i = 1; i <= 6; i++) {
            mySortedSet.Add(2 * i + 1);
        }
  
        // Displaying elements in mySortedSet
        Console.WriteLine("The elements in mySortedSet are : ");
  
        // Displaying the element in mySortedSet
        foreach(int i in mySortedSet)
        {
            Console.WriteLine(i);
        }
    }
}

chevron_right


Output:

The elements in mySortedSet are : 
3
5
7
9
11
13

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# code to create a SortedSet
using System;
using System.Collections.Generic;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
  
        // Creating a SortedSet of strings
        SortedSet<string> mySortedSet = new SortedSet<string>();
  
        // Adding elements in mySortedSet
        mySortedSet.Add("H");
        mySortedSet.Add("E");
        mySortedSet.Add("L");
        mySortedSet.Add("L");
        mySortedSet.Add("O");
  
        // Displaying elements in mySortedSet
        Console.WriteLine("The elements in mySortedSet are : ");
  
        // Displaying the element in mySortedSet
        foreach(string str in mySortedSet)
        {
            Console.WriteLine(str);
        }
    }
}

chevron_right


Output:

The elements in mySortedSet are : 
E
H
L
O


My Personal Notes arrow_drop_up

In love with a semicolon because sometimes i miss it so badly)

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.