How to create a SortedDictionary in C#

Introduction

A Dictionary type represents a collection of keys and values pair of data that is automatically sorted on the key.

The SortedDictionary class defined in the System.Collections.Generic namespace is a generic class and can store any data types in a form of keys and values. Each key must be unique in the collection. Before you use the Dictionary class in your code, you must import the System.Collections.Generic namespace using the following line.

using System.Collections.Generic;

Creating a SortedDictionary

The SortedDictionary class constructor takes a key data type and a value data type. Both types are generic so it can be any .NET data type.

The following The SortedDictionary class is a generic class and can store any data types. This class is defined in the code snippet creates a dictionary where both keys and values are string types.

SortedDictionary<string, string> EmployeeList = new SortedDictionary<string, string>();

The following code snippet adds items to the SortedDictionary. 

EmployeeList.Add("Mahesh Chand", "Programmer");
EmployeeList.Add("Praveen Kumar", "Project Manager");
EmployeeList.Add("Raj Kumar", "Architect");
EmployeeList.Add("Nipun Tomar", "Asst. Project Manager");
EmployeeList.Add("Dinesh Beniwal", "Manager");

The following code snippet creates a SortedDictionary where the key type is string and value type is short integer.

SortedDictionary<string, Int16> AuthorList = new SortedDictionary<string, Int16>();

The following code snippet adds items to the SortedDictionary. 

AuthorList.Add("Mahesh Chand", 35);
AuthorList.Add("Mike Gold", 25);
AuthorList.Add("Praveen Kumar", 29);
AuthorList.Add("Raj Beniwal", 21);
AuthorList.Add("Dinesh Beniwal", 84);



Learn more:

Working with SortedDictionary using C#


Up Next
    Ebook Download
    View all
    Learn
    View all