In C#, SortedList is a collection of key-value pairs sorted according to keys. By default, this collection sorts in ascending order. It is of both generic and non-generic type of collection. The generic SortedList is defined in the System.Collections.Generic namespace whereas non-generic SortedList is defined under System.Collections namespace, here we will discuss the non-generic type SortedList.
- Elements are sorted by key in ascending order.
- The keys are defined uniquely but we can store duplicate values.
- Offer to store data in keys and value pairs.
- No need to define the size we can add elements without giving the size like arrays.
Example:
using System;
using System.Collections.Generic;
class Geeks
{
public static void Main()
{
// Creating a SortedList
SortedList<int, string> sl = new SortedList<int, string>();
// Adding key-value pairs
sl.Add(3, "Three");
sl.Add(1, "One");
sl.Add(2, "Two");
// Displaying elements sorted by key
foreach (var item in sl)
{
Console.WriteLine($"Key: {item.Key}, Value: {item.Value}");
}
}
}
Output
Key: 1, Value: One Key: 2, Value: Two Key: 3, Value: Three
Steps to Create SortedList
We can use the SortedList Class which provides different ways to create a Sorted list. Here, we use the SortedList Class constructor to create a sorted list. Which is used to create an instance of the SortedList class that is empty by default and sorted according to the IComparable interface implemented by each key added to the SortedList object.
Step 1: Include System.Collections namespace
using System.Collections;
Step 2: Create a SortedList using the SortedList class
SortedList list_name = new SortedList();
Performing Different Operations on SortedList
1. Adding Elements
For adding elements list, The SortedList class provides the following methods:
- Add() : This method is used to add an object to the SortedList<T>.
- Collection Initializer: We can use Collection Initializer to add elements in SortedList<TKey, TValue>.
Syntax:
// Add element using Add method
list.Add(key, value);// Adding elements using the
// Collection initializers
SortedList<TKey, TValue> mySortedList = new SortedList<int, string>(){
{ key, value },
{ key, value },
};
Example: Creating sortedList using different ways.
using System;
using System.Collections;
class Geeks {
static public void Main() {
// Creating a sortedlist
// Using SortedList class
SortedList sl = new SortedList();
// Adding key-value pairs in
// SortedList using Add() method
sl.Add(1.02, "This");
sl.Add(1.07, "Is");
sl.Add(1.04, "SortedList");
foreach(DictionaryEntry pair in sl)
{
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);
}
}
}
Output
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
2. Accessing SortedList
There are three different ways to access the elements of the SortedList as it is stored in the Key-Value pair we can get the Key and value separately.
Using for Loop: We can use Loop to iterate through the list and access key-value pairs we can use List.GetKey() method to access the key and similarly from the key we can access the value by using List.GetByIndex(key).
Syntax:
for (int i = 0; i < sList.Count; i++)
{
Console.WriteLine("{0} and {1}",
sList.GetKey(i), // Accessing keys
sList.GetByIndex(i)); // Accessing values
}
Using ForEach Loop: We can use a foreach loop to access the key-value pairs of the SortedList. In the foreach loop, we can use a dictionary. It is mostly used to access the list stored in key-value pairs.
Syntax:
foreach(DictionaryEntry pair in my_slist1)
{
Console.WriteLine("{0} and {1}",
pair.Key, pair.Value);
}
Using Indexers: We can access the individual value of the SortedList by using the index. We need to pass the key or index as a parameter to find the respective value. It is similar to how we access the array.
Syntax:
Console.WriteLine("Value is:{0}", my_slist1[1.04]);
string x = (string)my_slist[1.02];
Console.WriteLine(x);
Note: If the specified key is not available, then the a runtime exception will be thrown (KeyNotFoundException).
Example: Demonstration of accessing SortedList in different ways.
using System;
using System.Collections;
class Geeks
{
static void Main()
{
SortedList sl = new SortedList {
{ 1, "Geek1" }, { 2, "Geek2" }, { 3, "Geek3" }
};
// Using for loop
Console.WriteLine("Access using for loop");
for (int i = 0; i < sl.Count; i++)
Console.WriteLine($"{sl.GetKey(i)}: {sl.GetByIndex(i)}");
// Using foreach loop
Console.WriteLine("Access using foreach loop");
foreach (DictionaryEntry entry in sl)
Console.WriteLine($"{entry.Key}: {entry.Value}");
// Using indexer
Console.WriteLine("Access using indexer");
Console.WriteLine($"Key 2: {sl[2]}" );
}
}
Output
Access using for loop 1: Geek1 2: Geek2 3: Geek3 Access using foreach loop 1: Geek1 2: Geek2 3: Geek3 Access using indexer Key 2: Geek2
3. Removing Elements
- Clear: This method is used to remove all elements from a SortedList object.
- Remove: This method is used to remove the element with the specified key from a SortedList object.
- RemoveAt: This method is used to remove the element at the specified index of a SortedList object.
Example:
using System;
using System.Collections;
class Geeks
{
static public void Main()
{
// Creating a sortedlist
// Using SortedList class
SortedList sl = new SortedList();
// Adding key/value pairs in SortedList
// Using Add() method
sl.Add(1, "one");
sl.Add(2, "two");
sl.Add(3, "three");
foreach(DictionaryEntry pair in sl)
{
Console.WriteLine("{0} and {1}",
pair.Key, pair.Value);
}
Console.WriteLine();
// Remove value having 1.07 key
// Using Remove() method
sl.Remove(1);
// After Remove() method
foreach(DictionaryEntry pair in sl)
{
Console.WriteLine("{0} and {1}",
pair.Key, pair.Value);
}
Console.WriteLine();
// Remove element at index 2
// Using RemoveAt() method
sl.RemoveAt(1);
// After RemoveAt() method
foreach(DictionaryEntry pair in sl)
{
Console.WriteLine("{0} and {1}",
pair.Key, pair.Value);
}
Console.WriteLine();
// Remove all key/value pairs
// Using Clear method
sl.Clear();
Console.WriteLine("Total pairs"+
" present in sorted list is: {0}", sl.Count);
}
}
Output
1 and one 2 and two 3 and three 2 and two 3 and three 2 and two Total pairs present in sorted list is: 0
4. Check Element
We can check the element of the SortedList by using the methods available below it returns value in boolean if the the element present returns true either false.
- 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:
using System;
using System.Collections;
class Geeks
{
static public void Main()
{
// Creating a sortedlist
// Using SortedList class
SortedList sl = new SortedList();
// Adding key-value pairs in
// SortedList using Add() method
sl.Add(1, "one");
sl.Add(2, "two");
sl.Add(3, "three");
// Using Contains() method to check
// the specified key is present or not
if (sl.Contains(1))
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 (sl.ContainsKey(2))
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 (sl.ContainsValue("one"))
Console.WriteLine("Value is found...!!");
else
Console.WriteLine("Value is not found...!!");
}
}
Output
Key is found...!! Key is found...!! Value is found...!!
Important Points
- SortedList implements interfaces like IEnumerable, ICollection, IDictionary, and ICloneable, and elements can be accessed using both key and index.
- It internally uses two arrays (keys and values), where keys cannot be null, must be unique, and of the same type, while values can be null and can be of same or different types (in non-generic version). er exception.
- The capacity defines how many key-value pairs it can hold, and key/value pairs can also be cast to DictionaryEntry.
- We can also cast key/value pair of SortedList into DictionaryEntry.