C# SortedList
Last Updated on June 18, 2022C# SortedList
In C# the SortedList collection stores key-value pairs in ascending order of the key. C# can support both generic and non-generic SortedList collections. We always recommended using the generic type of collection to perform the program faster and less error-prone than the non-generic type of SortedList.
Let’s see some examples of SortedList in C#.
using System;
using System.Collections.Generic;
namespace ConsoleAppDemo
{
class Program
{
static void Main(string[] args)
{
SortedList<int, string> langsLists = new SortedList<int, string>();
langsLists.Add(1,"C#");
langsLists.Add(2, "JavaScript");
langsLists.Add(3, "Java");
langsLists.Add(4, "Python");
//One way to access the value of the SortedList collection
Console.WriteLine(langsLists[1]); //Output: C#
//Seond way to access the value of the SortedList collection using the loops
foreach (KeyValuePair<int, string> lang in langsLists)
{
Console.WriteLine(lang.Key + " " + lang.Value);
}
//Third way to access the value of the List collection using the for loops
for (int i = 0; i < langsLists.Count; i++)
{
Console.WriteLine(langsLists.Keys[i] + " " + langsLists.Values[i]);
}
Console.ReadKey();
}
}
}
The output of both the Foreach and For loops:
1 C# 2 JavaScript 3 Java 4 Python
Alright, let's see another example with collection-initializer syntax.
using System;
using System.Collections.Generic;
namespace ConsoleAppDemo
{
class Program
{
static void Main(string[] args)
{
SortedList<int, string> langsLists = new SortedList<int, string>() {
{ 1,"C#" },
{ 2, "JavaScript" },
{ 3, "Java" },
{ 4, "Python" }
};
//One way to access the value of the List collection
Console.WriteLine(langsLists[1]); //Output: 1:C#
//Seond way to access the value of the SortedList collection using the loops
foreach (KeyValuePair<int, string> lang in langsLists)
{
Console.WriteLine(lang.Key + " " + lang.Value);
}
//Third way to access the value of the SortedList collection using the for loops
for (int i = 0; i < langsLists.Count; i++)
{
Console.WriteLine(langsLists.Keys[i] + " " + langsLists.Values[i]);
}
Console.ReadKey();
}
}
}
The output of both the Foreach and For loops:
1 C# 2 JavaScript 3 Java 4 Python