Member-only story

SortedSet in C# with Examples

Shahzad Aslam
2 min readApr 11, 2024

--

SortedSet is related to System.Collections.Generic namespace. A SortedSet is a collection that stored elements in sorted order. When you have need of storing elements in sorted order, In such type of situation you can use SortedSet.

Features with sortedset in C#:

Creating a SortedSet:

You will use System.Collections.Generic namespace for creating SortedSet. A SortedSet of sorted element can be create in the below way.

Example

using System;
using System.Collections.Generic;
SortedSet<int> fruitprices = new SortedSet<int>();
SortedSet<string> fruitnames = new SortedSet<string>();

Adding Elements:

You can add elements to a SortedSet using the Add method:

Example

fruitprices.Add(10);
fruitprices.Add(18);
fruitprices.Add(34);
fruitnames.Add("Apple");
fruitnames.Add("Banana");
fruitnames.Add("Cherry");

Accessing Elements:

By using the foreach loop the elements in a SortedSet can be access.

Example

foreach (int price in fruitprices)
{
Console.WriteLine(price);
}
bool contains = fruitprices.Contains(18); // Returns true
foreach…

--

--

Shahzad Aslam
Shahzad Aslam

Written by Shahzad Aslam

Welcome to c-sharptutorial.com. I am Shahzad Aslam. I am the founder of c-sharptutorial.com. I'm currently living near Islamabad, Pakistan.

Responses (1)