C# SortedSet<T>

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.

snippet
using System;
using System.Collections.Generic;

public class SortedSetExample
{
    public static void Main(string[] args)
    {
        // Create a set of strings
        var names = new SortedSet();
        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.

snippet
using System;
using System.Collections.Generic;

public class SortedSetExample
{
    public static void Main(string[] args)
    {
        // Create a set of strings
        var names = new SortedSet(){"Sonoo", "Ankit", "Peter", "Irfan"};
        
        // Iterate SortedSet elements using foreach loop
        foreach (var name in names)
        {
            Console.WriteLine(name);
        }
    }
}

Output:

Output
Ankit Irfan Peter Sonoo
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents