C Sharp SortedSet

C# SortedSet<T>

To store elements in ascending order or to remove or view the stored elements in C#, the SortedSet class is used which is found in the System.Collections.Generic namespace. The duplicate elements can not be stored by the SortedSet class in C#, thus it is used to store the unique elements in ascending order.

Example:

using System;  
using System.Collections.Generic;  
 
public class Example  
{  
    public static void Main(string[] args)  
    {  
        // Create a set of strings  
        var countries = new SortedSet();  
        countries.Add("Japan");  
        countries.Add("Australia");  
        countries.Add("India");  
        countries.Add("Nepal");  
        countries.Add("Canada");
 
        // Iterate SortedSet elements using foreach loop  
        foreach (var country in countries)  
        {  
            Console.WriteLine(country);  
        }  
    }  
}

Output:

Explanation:

In the above example, we are using the generic SortedSet<T> class. The Add() method is used to store elements and the for-each loop is used to iterate the elements.

Example:

using System;  
using System.Collections.Generic;  
 
public class Example  
{  
    public static void Main(string[] args)  
    {  
        // Create a set of strings  
        var countries = new SortedSet(){"India", "Australia", "Canada", "Mexico", "Japan"};  
 
        // Iterate HashSet elements using foreach loop  
        foreach (var country in countries)  
        {  
            Console.WriteLine(country);  
        }  
    }  
}

Output:

Explanation:

In the above example, we are using the generic SortedSet<T> class to store elements using the Collection initializer.

Please follow and like us:
Content Protection by DMCA.com