Dark Mode
Image

C# Properties

C# Inheritance

C# Polymorphism

C# Strings

C# Generics

C# Delegates

C# Reflection

Anonymous Function

C# Multithreading

C# Synchronization

C# Web Service

C# Misc

C# New Features

C# Programs

ADO.NET Tutorial

ASP.NET Tutorial

C# SortedList

 

C# SortedList is an array of key/value pairs. It stores values on the basis of key. The SortedList class contains unique keys and maintains ascending order on the basis of key. By the help of key, we can easily search or remove elements. It is found in System.Collections.Generic namespace.

It is like SortedDictionary class.

C# SortedList vs SortedDictionary

SortedList class uses less memory than SortedDictionary. It is recommended to use SortedList if you have to store and retrieve key/valye pairs. The SortedDictionary class is faster than SortedList class if you perform insertion and removal for unsorted data.

C# SortedList example

Let's see an example of generic SortedList class that stores elements using Add() method and iterates elements using for-each loop. Here, we are using KeyValuePair class to get key and value.

using System;  
using System.Collections.Generic;  
  
public class SortedDictionaryExample  
{  
    public static void Main(string[] args)  
    {  
        SortedList names = new SortedList();  
        names.Add("1","Sunil");    
        names.Add("4","Anil");    
        names.Add("5","Mathew");    
        names.Add("3","pushkar");    
        names.Add("2","sujit");    
        foreach (KeyValuePair kv in names)  
        {  
            Console.WriteLine(kv.Key+" "+kv.Value);  
        }  
    }  
}    

Output:

1 Sunil
2 Sujit 
3 Pushkar
4 Anil
5 Mathew

Comment / Reply From