C# Sortedset

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<T> class that stores elements using Add method and iterates elements using for-each loop.

Example

using System;

using System.Collections.Generic;



public class SortedSetExample

{

    public static void Main(string[] args)

    {

        // Create a set of strings

        var names = new SortedSet<string>();

        names.Add("Sonoo");

        names.Add("Ankit");

        names.Add("Peter");

        names.Add("Irfan");

        names.Add("Ankit");//will not be added

        

        // Iterate SortedSet elements using foreach loop

        foreach (var name in names)

        {

            Console.WriteLine(name);

        }

    }

}

Output:

Output

Ankit

Irfan

Peter

Sonoo

C# SortedSet<T> example 2

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

Example

using System;

using System.Collections.Generic;



public class SortedSetExample

{

    public static void Main(string[] args)

    {

        // Create a set of strings

        var names = new SortedSet<string>(){"Sonoo", "Ankit", "Peter", "Irfan"};

        

        // Iterate SortedSet elements using foreach loop

        foreach (var name in names)

        {

            Console.WriteLine(name);

        }

    }

}

Output:

Output

Ankit

Irfan

Peter

Sonoo

Input Required

This code uses input(). Please provide values below: