What is the role of SortedList<K, V> in C#, and why are use this collection in C# explain with example?

Asked 27-Aug-2021
Viewed 860 times

0

What is the role of SortedList<K, V> in C#, and why are use this collection in C# explain with example?


1 Answer


0

SortedList<K, V>

SortedList<K, V> is used for storing the value in sorted order on behalf of the key. SortedList<K, V> in a generic class of System.Collections.Generic. 

Syntax

SortedList<K, V> list=new SortedList<K, V>();

Example

using System;

using System.Collections.Generic;
public class Program
{
 public static void Main()
 {
  SortedList<int, string> list=new SortedList<int, string>();
  list.Add(0,'Ashu');
  list.Add(2,'Shyam');
  list.Add(1,'Sunny');
  list.Add(3,'Jira');
  list.Add(4,'DB');
  Console.WriteLine('Count ; '+list.Count);
  Console.WriteLine('Capacity : '+list.Capacity);
  foreach(var item in list)
   Console.WriteLine(item + ' Key : ' + item.Key + ' Value : ' + item.Value);
 }
}

Output

Count ; 5

Capacity : 8
[0, Ashu] Key : 0 Value : Ashu
[1, Sunny] Key : 1 Value : Sunny
[2, Shyam] Key : 2 Value : Shyam
[3, Jira] Key : 3 Value : Jira
[4, DB] Key : 4 Value : DB