SortedDictionary Implementation in C#
Last Updated :
25 Sep, 2023
In C#, SortedDictionary is a generic collection that is used to store the key/value pairs in the sorted form and the sorting is done on the key. SortedDictionary is defined under System.Collection.Generic namespace. It is dynamic in nature means the size of the sorted dictionary is growing according to the need. Important Points:
- The SortedDictionary class implements the
- ICollection<KeyValuePair<TKey, TValue>> Interface
- IDictionary<TKey, TValue> Interface
- IEnumerable<KeyValuePair<TKey, TValue>> Interface
- IEnumerable<T> Interface
- IReadOnlyCollection<KeyValuePair<TKey, TValue>> Interface
- IReadOnlyDictionary<TKey, TValue> Interface
- ICollection Interface
- IDictionary Interface
- IEnumerable Interface
- In SortedDictionary, the key must be unique. Duplicate keys are not allowed.
- In SortedDictionary, the keys are immutable and cannot be null.
- In SortedDictionary, the value can be null when the type of the value is of reference type.
- It provides fastest insertion and removal operations for unsorted data.
- In SortedDictionary, you can only store the same types of key/value pairs.
- The capacity of a SortedDictionary is the number of key/value pairs that SortedDictionary can hold.
- It sort in ascending order.
How to create a SortedDictionary?
A SortedDictionary class has 4 constructors which are used to create a SortedDictionary and the constructors are as follows:
- SortedDictionary<TKey, TValue>(): This constructor is used to create an instance of the SortedDictionary class that is empty and uses the default IComparer implementation for the key type.
- SortedDictionary<TKey, TValue>(IComparer): This constructor is used to create an instance of the SortedDictionary class that is empty and uses the specified IComparer implementation to compare keys.
- SortedDictionary<TKey, TValue>(IDictionary): This constructor is used to create an instance of the SortedDictionary class that contains elements copied from the specified IDictionary and uses the default IComparer implementation for the key type.
- SortedDictionary<TKey, TValue>(IDictionary, IComparer): This constructor is used to create an instance of the SortedDictionary class that contains elements copied from the specified IDictionary and uses the specified IComparer implementation to compare keys.
Let’s see how to create a SortedDictionary using SortedDictionary<TKey, TValue>() constructor: Step 1: Include System.Collection.Generics namespace in your program with the help of using keyword.
using System.Collection.Generics;
Step 2:Create a SortedDictionary using SortedDictionary<TKey, TValue> class as shown below:
SortedDictionary<Type_of_key, Type_of_value> sorteddictionary_name = new SortedDictionary<Type_of_key, Type_of_value>();
Step 3: If you want to add elements in your SortedDictionary then use Add() method to add a key/value pairs in your SortedDictionary. And you can also add key/value pair in the SortedDictionary using Collection Initializer. Step 4: The key/value pair of the SortedDictionary is accessed by using a foreach loop, or by using index value, or by using for loop. Example:
CSharp
// C# program to illustrate how
// to create sorted dictionary
using System;
using System.Collections.Generic;
class GFG {
// Main Method
static public void Main()
{
// Creating sorted dictionary
// Using SortedDictionary class
SortedDictionary<int, string> My_sdict =
new SortedDictionary<int, string>();
// Adding key/value pair in Sorted
// Dictionary Using Add() method
My_sdict.Add(004, "Ask.com");
My_sdict.Add(003, "Yahoo");
My_sdict.Add(001, "Google");
My_sdict.Add(005, "AOL.com");
My_sdict.Add(002, "Bing");
Console.WriteLine("Top Search Engines:");
// Accessing the key/value pair of the
// SortedDictionary Using foreach loop
foreach(KeyValuePair<int, string> pair in My_sdict)
{
Console.WriteLine("Rank: {0} and Name: {1}",
pair.Key, pair.Value);
}
// Creating another sorted dictionary
// using SortedDictionary<TKey, TValue> class
// adding key/value pairs
// Using collection initializer
SortedDictionary<int, string> My_sdict1 =
new SortedDictionary<int, string>() {
{1, "Python"},
{5, "Swift"},
{2, "JavaScript"},
{4, "Go" },
{3, "Rust"}};
Console.WriteLine("Top Programming Language in 2019: ");
// Accessing the key/value pair of the
// SortedDictionary Using foreach loop
foreach(KeyValuePair<int, string> pair in My_sdict1)
{
Console.WriteLine("Rank:{0} and Name: {1}",
pair.Key, pair.Value);
}
}
}
OutputTop Search Engines:
Rank: 1 and Name: Google
Rank: 2 and Name: Bing
Rank: 3 and Name: Yahoo
Rank: 4 and Name: Ask.com
Rank: 5 and Name: AOL.com
Top Programming Language in 2019:
Rank:1 and Name: Python
Rank:2 and Name: JavaScript
Rank:3 and Name: Rust
Rank:4 and Name: Go
Rank:5 and Name: Swift
How to remove elements from the SortedDictionary?
In SortedDictionary, it is allowed to remove elements from the SortedDictionary. SortedDictionary<TKey, TValue> class provides two different methods to remove elements and the methods are:
- Clear(): This method is used to remove all elements from the SortedDictionary.
- Remove(TKey): This method is used to remove the element with the specified key from the SortedDictionary.
Example:
CSharp
// C# program to illustrate how to
// Remove key/value pair from the
// SortedDictionary
using System;
using System.Collections.Generic;
class GFG {
// Main Method
static public void Main()
{
// Creating sorted dictionary
// Using SortedDictionary class
SortedDictionary<int, string> My_sdict =
new SortedDictionary<int, string>();
// Adding key/value pair in
// SortedDictionary Using
// the Add() method
My_sdict.Add(001, "Google");
My_sdict.Add(002, "Bing");
My_sdict.Add(003, "Yahoo");
My_sdict.Add(004, "Ask.com");
My_sdict.Add(005, "AOL.com");
// Initial number of key/value pairs
Console.WriteLine("Key/Value pair: {0}",
My_sdict.Count);
// After using Remove(TKey) method
My_sdict.Remove(002);
Console.WriteLine("Key/Value pair: {0}",
My_sdict.Count);
// After using Clear() method
My_sdict.Clear();
Console.WriteLine("Key/Value pair: {0}",
My_sdict.Count);
}
}
OutputKey/Value pair: 5
Key/Value pair: 4
Key/Value pair: 0
How to check the availability of key/value pair in the SortedDictionary?
In SortedDictionary, you can check whether the given key or value present in the specified SortedDictionary or not. The SortedDictionary<TKey, TValue> class provides two different methods for checking and the methods are:
- ContainsKey(TKey): This method is used to determine whether the SortedDictionary contains an element with the specified key.
- ContainsValue(TValue): This method is used to determine whether the SortedDictionary contains an element with the specified value.
Example:
CSharp
// C# program to illustrate how to
// check the given key/value pair
// is exists or not in SortedDictionary
using System;
using System.Collections.Generic;
class GFG {
// Main Method
static public void Main()
{
// Creating sorted dictionary
// Using SortedDictionary class
SortedDictionary<int, string> My_sdict =
new SortedDictionary<int, string>();
// Adding key/value pair
// in SortedDictionary
// Using Add() method
My_sdict.Add(001, "Google");
My_sdict.Add(002, "Bing");
My_sdict.Add(003, "Yahoo");
My_sdict.Add(004, "Ask.com");
My_sdict.Add(005, "AOL.com");
// Using ContainsKey(TKey) method
if (My_sdict.ContainsKey(004) == true)
{
Console.WriteLine("Key Found..");
}
else
{
Console.WriteLine("Key Not Found..");
}
// Using ContainsValue(TValue) method
if (My_sdict.ContainsValue("Baidu") == true)
{
Console.WriteLine("Value Found..");
}
else
{
Console.WriteLine("Value Not Found..");
}
}
}
OutputKey Found..
Value Not Found..
How to access all the elements from the SortedDictionary?
To access elements in a SortedDictionary by key in C#, you can use the indexing operator or the TryGetValue() method.
Here's a brief summary of the TryGetValue() method:
- It attempts to retrieve the value associated with a specified key from the SortedDictionary.
- If the key is found, the method assigns the corresponding value to the out parameter and returns true.
- If the key is not found, the out parameter is assigned the default value for its type (e.g., 0 for int) and the method returns false.
Here's an example:
C#
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// Create a SortedDictionary
SortedDictionary<string, int> dictionary = new SortedDictionary<string, int>();
// Add some key-value pairs
dictionary.Add("Apple", 5);
dictionary.Add("Banana", 3);
dictionary.Add("Orange", 8);
// Access elements by key using indexing operator
int appleCount = dictionary["Apple"];
int orangeCount = dictionary["Orange"];
Console.WriteLine($"Apple count: {appleCount}"); // Output: Apple count: 5
Console.WriteLine($"Orange count: {orangeCount}"); // Output: Orange count: 8
// Access elements by key using TryGetValue() method
int bananaCount;
if (dictionary.TryGetValue("Banana", out bananaCount))
{
Console.WriteLine($"Banana count: {bananaCount}"); // Output: Banana count: 3
}
else
{
Console.WriteLine("Banana not found in the dictionary");
}
// Accessing an element with a non-existent key will throw a KeyNotFoundException
// To avoid this, you can use the TryGetValue() method as shown above to check for key existence before accessing the value.
Console.ReadLine();
}
}
OutputApple count: 5
Orange count: 8
Banana count: 3
In the above example, we create a SortedDictionary with string keys and integer values. We add some key-value pairs to the dictionary. Then, we access the elements by key using the indexing operator (dictionary["key"]) and the TryGetValue() method (dictionary.TryGetValue(key, out value)). Finally, we display the retrieved values on the console.
Note that when using the indexing operator, if the specified key does not exist in the SortedDictionary, it will throw a KeyNotFoundException. Therefore, it's recommended to use the TryGetValue() method when there's a possibility of the key not existing in the dictionary to handle such scenarios gracefully.
How to clear all the elements from the SortedDictionary?
To clear all elements from a SortedDictionary in C#, you can use the Clear() method.
C#
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
SortedDictionary<string, int> dictionary = new SortedDictionary<string, int>();
// Add key-value pairs to the SortedDictionary
dictionary.Add("Apple", 10);
dictionary.Add("Banana", 5);
dictionary.Add("Orange", 8);
// Clear all elements from the SortedDictionary
dictionary.Clear();
// Verify that the SortedDictionary is empty
Console.WriteLine("Number of elements in the SortedDictionary: " + dictionary.Count);
}
}
OutputNumber of elements in the SortedDictionary: 0
In this example, we create a SortedDictionary with string keys and int values. We add three key-value pairs to the dictionary using the Add method. Then, we clear all elements from the SortedDictionary using the Clear method. Finally, we display the count of elements in the SortedDictionary, which should be 0 since we cleared all the elements.
Similar Reads
Introduction
C# TutorialC# (pronounced "C-sharp") is a modern, versatile, object-oriented programming language developed by Microsoft in 2000 that runs on the .NET Framework. Whether you're creating Windows applications, diving into Unity game development, or working on enterprise solutions, C# is one of the top choices fo
4 min read
Introduction to .NET FrameworkThe .NET Framework is a software development framework developed by Microsoft that provides a runtime environment and a set of libraries and tools for building and running applications on Windows operating systems. The .NET framework is primarily used on Windows, while .NET Core (which evolved into
6 min read
C# .NET Framework (Basic Architecture and Component Stack)C# (C-Sharp) is a modern, object-oriented programming language developed by Microsoft in 2000. It is a part of the .NET ecosystem and is widely used for building desktop, web, mobile, cloud, and enterprise applications. This is originally tied to the .NET Framework, C# has evolved to be the primary
6 min read
C# Hello WorldThe Hello World Program is the most basic program when we dive into a new programming language. This simply prints "Hello World!" on the console. In C#, a basic program consists of the following:A Namespace DeclarationClass Declaration & DefinitionClass Members(like variables, methods, etc.)Main
4 min read
Common Language Runtime (CLR) in C#The Common Language Runtime (CLR) is a component of the Microsoft .NET Framework that manages the execution of .NET applications. It is responsible for loading and executing the code written in various .NET programming languages, including C#, VB.NET, F#, and others.When a C# program is compiled, th
4 min read
Fundamentals
C# IdentifiersIn programming languages, identifiers are used for identification purposes. Or in other words, identifiers are the user-defined name of the program components. In C#, an identifier can be a class name, method name, variable name, or label. Example: public class GFG { static public void Main () { int
2 min read
C# Data TypesData types specify the type of data that a valid C# variable can hold. C# is a strongly typed programming language because in C# each type of data (such as integer, character, float, and so forth) is predefined as part of the programming language and all constants or variables defined for a given pr
7 min read
C# VariablesIn C#, variables are containers used to store data values during program execution. So basically, a Variable is a placeholder of the information which can be changed at runtime. And variables allows to Retrieve and Manipulate the stored information. In Brief Defination: When a user enters a new valu
4 min read
C# LiteralsIn C#, a literal is a fixed value used in a program. These values are directly written into the code and can be used by variables. A literal can be an integer, floating-point number, string, character, boolean, or even null. Example:// Here 100 is a constant/literal.int x = 100; Types of Literals in
5 min read
C# OperatorsIn C#, Operators are special types of symbols which perform operations on variables or values. It is a fundamental part of language which plays an important role in performing different mathematical operations. It takes one or more operands and performs operations to produce a result.Types of Operat
7 min read
C# KeywordsKeywords or Reserved words are the words in a language that are used for some internal process or represent some predefined actions. These words are therefore not allowed to be used as variable names or objects. Doing this will result in a compile-time error.Example:C#// C# Program to illustrate the
5 min read
Control Statements
C# Decision Making (if, if-else, if-else-if ladder, nested if, switch, nested switch)Decision Making in programming is similar to decision making in real life. In programming too, a certain block of code needs to be executed when some condition is fulfilled. A programming language uses control statements to control the flow of execution of program based on certain conditions. These
5 min read
C# Switch StatementIn C#, Switch statement is a multiway branch statement. It provides an efficient way to transfer the execution to different parts of a code based on the value of the expression. The switch expression is of integer type such as int, char, byte, or short, or of an enumeration type, or of string type.
4 min read
C# LoopsLooping in a programming language is a way to execute a statement or a set of statements multiple times, depending on the result of the condition to be evaluated to execute statements. The result condition should be true to execute statements within loops.Types of Loops in C#Loops are mainly divided
4 min read
C# Jump Statements (Break, Continue, Goto, Return and Throw)In C#, Jump statements are used to transfer control from one point to another point in the program due to some specified code while executing the program. In, this article, we will learn to different jump statements available to work in C#.Types of Jump StatementsThere are mainly five keywords in th
4 min read
OOP Concepts
Methods
Arrays
C# ArraysAn array is a group of like-typed variables that are referred to by a common name. And each data item is called an element of the array. The data types of the elements may be any valid data type like char, int, float, etc. and the elements are stored in a contiguous location. Length of the array spe
8 min read
C# Jagged ArraysA jagged array is an array of arrays, where each element in the main array can have a different length. In simpler terms, a jagged array is an array whose elements are themselves arrays. These inner arrays can have different lengths. Can also be mixed with multidimensional arrays. The number of rows
4 min read
C# Array ClassArray class in C# is part of the System namespace and provides methods for creating, searching, and sorting arrays. The Array class is not part of the System.Collections namespace, but it is still considered as a collection because it is based on the IList interface. The Array class is the base clas
7 min read
How to Sort an Array in C# | Array.Sort() Method Set - 1Array.Sort Method in C# is used to sort elements in a one-dimensional array. There are 17 methods in the overload list of this method as follows:Sort<T>(T[]) MethodSort<T>(T[], IComparer<T>) MethodSort<T>(T[], Int32, Int32) MethodSort<T>(T[], Comparison<T>) Method
8 min read
How to find the rank of an array in C#Array.Rank Property is used to get the rank of the Array. Rank is the number of dimensions of an array. For example, 1-D array returns 1, a 2-D array returns 2, and so on. Syntax: public int Rank { get; } Property Value: It returns the rank (number of dimensions) of the Array of type System.Int32. B
2 min read
ArrayList
String
Tuple
Indexers