Introduction
In C#, the SortedList class represents a collection of key/value pairs sorted by the keys and accessible by key and index. SortedList in C# is a generic collection defined as SortedList<TKey, TValue>, where Tkey is the collection's key type, and Tvalue is the collection's value type.
A sorted list is a hash table and an array combined. It includes a list of items that can be accessed using a key or index. It's an ArrayList if you access items by index, and it's a Hashtable if you access items by key. The key value is always used to sort the collection of items.
Recommended Topic, Palindrome in C#, singleton design pattern in c# and Ienumerable vs Iqueryable
C# SortedList Example
Here is a C# program to illustrate how to create a sortedList.
using System;
using System.Collections;
class Codingninjas
{
static void Main(string[] args)
{
SortedList sorted_list=new SortedList();
sorted_list.Add("1.00", "Rishi");
sorted_list.Add("2.00", "Alok");
sorted_list.Add("3.00", "Priyanshu");
sorted_list.Add("4.00", "Ayush");
sorted_list.Add("5.00", "Mohini");
if (sorted_list.ContainsValue("Javed"))
{
Console.WriteLine("This student name is already exist in the list");
}
else
{
sorted_list.Add("6.00", "Javed");
}
// getting a collection of the keys.
ICollection key=sorted_list.Keys;
foreach (string str in key)
{
Console.WriteLine(str+": "+sorted_list[str]);
}
}
}
Output
1.00: Rishi
2.00: Alok
3.00: Priyanshu
4.00: Ayush
5.00: Mohini
6.00: Javed