Member-only story

SortedDictionary in C# with Examples

Shahzad Aslam
3 min readApr 18, 2024

--

The SortedDictionary is related to System.Collections.Generic namespace. SortedDictionary contains on key-value pairs. Where the keys are automatically sorted in ascending order.

SortedDictionary in C# With Examples

Features with sorteddictionary in C#:

Creating a SortedDictionary:

You must use System.Collections.Generic before use of SortedDictionary. You can use the following syntax to create the SortedDictionary.

using System;
using System.Collections.Generic;
SortedDictionary<string,int> dictfruitprices = new SortedDictionary<string,int>();
SortedDictionary<string,string> dictfruitnames = new SortedDictionary<string,string>();

Adding Key-Value Pairs:

You can add key-value pairs to a SortedDictionary using the Add method or by using the indexer:

Example

dictfruitprices.Add("Apple",16);
dictfruitprices.Add("Orange",12);
dictfruitprices.Add("Cherry",18);
dictfruitprices["Papaya"] = 20;
dictfruitprices["Grape"] = 6;
dictfruitnames.Add("Apple","Red");
dictfruitnames.Add("Mango","Yellow");
dictfruitnames.Add("Cherry","Red");
dictfruitnames.Add("Orange","Dark Orange");
dictfruitnames["Grape"] = "Violet";
dictfruitnames.["Kiwi"] = "Spring Green";

--

--

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.

No responses yet