Open In App

C# | How to create a SortedSet

Last Updated : 01 Feb, 2019
Comments
Improve
Suggest changes
Like Article
Like
Report
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: CSHARP
// 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);
        }
    }
}
Output:
The elements in mySortedSet are : 
3
5
7
9
11
13
Example 2: CSHARP
// 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);
        }
    }
}
Output:
The elements in mySortedSet are : 
E
H
L
O

Next Article

Similar Reads