C# SortedList with Examples - GeeksforGeeks

13 Jul, 2021
In C#, SortedList is a collection of key/value pairs which are sorted according to keys. By default, this collection sort the key/value pairs in ascending order. It is of both generic and non-generic type of collection. The generic SortedList is defined in System.Collections.Generic namespace whereas non-generic SortedList is defined under System.Collections namespace, here we will discuss non-generic type SortedList. Important Points:  
The SortedList class implements the IEnumerable, ICollection, IDictionary and ICloneable interfaces.
In SortedList, an element can be accessed by its key or by its index.
A SortedList object internally maintains two arrays to store the elements of the list, i.e, one array for the keys and another array for the associated values.
Here, a key cannot be null, but a value can be.
The capacity of a SortedList object is the number of key/value pairs it can hold.
In SortedList, duplicate keys are not allowed.
In SortedList, you can store values of the same type and of the different types due to the non-generic collection. If you use a generic SortedList in your program, then it is necessary that the type of the values should be the same.
In SortedList you cannot store keys of different data types in the same SortedList because the compiler will throw an exception. So, always add the key in your SortedList of the same type.
You can also cast key/value pair of SortedList into DictionaryEntry.
 
The SortedList class provides 6 different types of constructors which are used to create a SortedList, here we only use SortedList(), constructor. To read more about SortedList’s constructors you can refer to C# | SortedList Class.SortedList(): It is used to create an instance of the SortedList class that is empty, has the default initial capacity, and is sorted according to the IComparable interface implemented by each key added to the SortedList object. Step 1: Include System.Collections namespace in your program with the help of using keyword: 
using System.Collections;
Step 2: Create a SortedList using SortedList class as shown below: 
SortedList list_name = new SortedList();
Step 3: If you want to add a key/value pair in your SortedList, then use Add() method to add key/value pairs in your SortedList. And you can also store a key/value pair in your SortedList without using the Add() method, this type of syntax is known as Collection Initializer Syntax as shown in the below example.Step 4: The key/value pairs of the SortedList is accessed using three different ways: 
for loop: You can use for loop to access the key/value pairs of the SortedList.Example: 
CSharp
for (int x = 0; x < my_slist1.Count; x++){    Console.WriteLine("{0} and {1}",                my_slist1.GetKey(x),           my_slist1.GetByIndex(x));}
Using Index: You can access the individual value of the SortedList by using the index. You need to pass the key or index as a parameter to find the respective value. If the specified key is not available, then the compiler will throw an error.Example: 
CSharp
Console.WriteLine("Value is:{0}", my_slist1[1.04]); string x = (string)my_slist[1.02]; Console.WriteLine(x);
foreach loop: You can use a foreach loop to access the key/value pairs of the SortedList.Example: 
CSharp
foreach(DictionaryEntry pair in my_slist1){    Console.WriteLine("{0} and {1}",              pair.Key, pair.Value);}
Example: 
CSharp
// C# program to illustrate how// to create a sortedlistusing System;using System.Collections; class GFG {     // Main Method    static public void Main()    {         // Creating a sortedlist        // Using SortedList class        SortedList my_slist1 = new SortedList();         // Adding key/value pairs in        // SortedList using Add() method        my_slist1.Add(1.02, "This");        my_slist1.Add(1.07, "Is");        my_slist1.Add(1.04, "SortedList");        my_slist1.Add(1.01, "Tutorial");         foreach(DictionaryEntry pair in my_slist1)        {            Console.WriteLine("{0} and {1}",                      pair.Key, pair.Value);        }        Console.WriteLine();         // Creating another SortedList        // using Object Initializer Syntax        // to initialize sortedlist        SortedList my_slist2 = new SortedList() {                                  { "b.09", 234 },                                  { "b.11", 395 },                                  { "b.01", 405 },                                  { "b.67", 100 }};                         foreach(DictionaryEntry pair in my_slist2)        {            Console.WriteLine("{0} and {1}",                      pair.Key, pair.Value);        }    }}
1.01 and Tutorial
1.02 and This
1.04 and SortedList
1.07 and Is

b.01 and 405
b.09 and 234
b.11 and 395
b.67 and 100
 
Clear: This method is used to removes all elements from a SortedList object.
Remove: This method is used to removes the element with the specified key from a SortedList object.
RemoveAt: This method is used to removes the element at the specified index of a SortedList object.
Example: 
CSharp
// C# program to illustrate how to// remove key/value pairs from// the sortedlistusing System;using System.Collections; class GFG {     // Main Method    static public void Main()    {         // Creating a sortedlist        // Using SortedList class        SortedList my_slist = new SortedList();         // Adding key/value pairs in SortedList        // Using Add() method        my_slist.Add(1.02, "This");        my_slist.Add(1.07, "Is");        my_slist.Add(1.04, "SortedList");        my_slist.Add(1.01, "Tutorial");         foreach(DictionaryEntry pair in my_slist)        {            Console.WriteLine("{0} and {1}",                      pair.Key, pair.Value);        }        Console.WriteLine();         // Remove value having 1.07 key        // Using Remove() method        my_slist.Remove(1.07);         // After Remove() method        foreach(DictionaryEntry pair in my_slist)        {            Console.WriteLine("{0} and {1}",                      pair.Key, pair.Value);        }        Console.WriteLine();         // Remove element at index 2        // Using RemoveAt() method        my_slist.RemoveAt(2);         // After RemoveAt() method        foreach(DictionaryEntry pair in my_slist)        {            Console.WriteLine("{0} and {1}",                      pair.Key, pair.Value);        }        Console.WriteLine();         // Remove all key/value pairs        // Using Clear method        my_slist.Clear();        Console.WriteLine("The total number of key/value pairs"+                    " present in my_slist:{0}", my_slist.Count);    }}
1.01 and Tutorial
1.02 and This
1.04 and SortedList
1.07 and Is

1.01 and Tutorial
1.02 and This
1.04 and SortedList

1.01 and Tutorial
1.02 and This

The total number of key/value pairs present in my_slist:0
 
In SortedList, you can check whether the given pair is present or not using the following methods: 
Contains: This method is used to check whether a SortedList object contains a specific key.
ContainsKey: This method is used to check whether a SortedList object contains a specific key.
ContainsValue: This method is used to check whether a SortedList object contains a specific value.
Example: 
CSharp
// C# program to illustrate how to// check the given key or value// present in the sortedlist or notusing System;using System.Collections; class GFG {     // Main Method    static public void Main()    {         // Creating a sortedlist        // Using SortedList class        SortedList my_slist = new SortedList();         // Adding key/value pairs in        // SortedList using Add() method        my_slist.Add(1.02, "This");        my_slist.Add(1.07, "Is");        my_slist.Add(1.04, "SortedList");        my_slist.Add(1.01, "Tutorial");         // Using Contains() method to check        // the specified key is present or not        if (my_slist.Contains(1.02) == true)        {            Console.WriteLine("Key is found...!!");        }         else        {            Console.WriteLine("Key is not found...!!");        }         // Using ContainsKey() method to check        // the specified key is present or not        if (my_slist.ContainsKey(1.03) == true)        {            Console.WriteLine("Key is found...!!");        }        else        {            Console.WriteLine("Key is not found...!!");        }         // Using ContainsValue() method to check        // the specified value is present or not        if (my_slist.ContainsValue("Is") == true)        {            Console.WriteLine("Value is found...!!");        }         else        {            Console.WriteLine("Value is not found...!!");        }    }}
Key is found...!!
Key is not found...!!
Value is found...!!
 
anikakapoor
CSharp-Collections-Namespace
CSharp-Collections-SortedList
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between Abstract Class and Interface in C#
C# | How to check whether a List contains a specified element
C# | IsNullOrEmpty() Method
String.Split() Method in C# with Examples
C# | Arrays of Strings
Destructors in C#
Difference between Ref and Out keywords in C#
C# | Delegates
Extension Method in C#
C# | String.IndexOf( ) Method | Set - 1