C# Generic SortedList<TKey,Tvalue> with Programming Example

In this chapter you will learn
  • What is Generic SortedList<TKey,Tvalue> Programming in c#?
  • How to write program using Sorted List in C#?

C# Generic SortedList represents a collection of key/value pairs that are sorted by key based on the associated IComparer<T> implementation. It belongs to System.Collections.Generic namespace. It is similar to SortedDictionary but still there are some differences between them like

  1. SortedList uses less memory than SortedDictionary
  2. SortedDictionary has faster insertion and removal operations for unsorted data than SortedList
  3. If the list is populated all at once from sorted data then SortedList works faster than SortedDictionary.
  4. SortedList supports efficient indexed retrieval of keys and values.

SortedList doesn't allow inserting the null value and duplicate value. Every key in a SortedList must be unique otherwise it throws ArgumentException.

Initialization

SortedList<int,string> mySortedList = new SortedList<int,string>();

 

Important Properties and Methods of SortedList<TKey, TValue>

Properties Description
Capacity Gets or sets the number of elements that the SortedList<TKey,TValue> can store.
Count Gets the total number of elements exists in the SortedList<TKey,TValue>.
IsReadOnly Returns a boolean indicating whether the SortedList<TKey,TValue> is read-only.
Item Gets or sets the element with the specified key in the SortedList<TKey,TValue>.
Keys Get list of keys of SortedList<TKey,TValue>.
Values Get list of values in SortedList<TKey,Tvalue>.

Important Methods

Methods Description
void Add(TKey key, TValue value) Add key-value pairs into SortedList<TKey, TValue>.
void Remove(TKey key) Removes element with the specified key.
void RemoveAt(int index) Removes element at the specified index.
bool ContainsKey(TKey key) Checks whether the specified key exists in SortedList<TKey, TValue>.
bool ContainsValue(TValue value) Checks whether the specified key exists in SortedList<TKey, TValue>.
void Clear() Removes all the elements from SortedList<TKey, TValue>.
int IndexOfKey(TKey key) Returns an index of specified key stored in internal array of SortedList<TKey, TValue>.
int IndexOfValue(TValue value) Returns an index of specified value stored in internal array of SortedList<TKey, TValue>
bool TryGetValue(TKey key, out TValue value) Returns true and assigns the value with specified key, if key does not exists then return false.

Programming Example

using System;
using System.Collections.Generic;

namespace SortedList_Example
{
    public class Program
    {
        public static void Main(string[] args)
        {
            SortedList<int,string> studentlist=new SortedList<int,string>();
            //Adding some items to sorted list
            studentlist.Add(1,"Jack");
            studentlist.Add(2,"Mark");
            studentlist.Add(3,"Neo");
            studentlist.Add(4,"Steven");
            studentlist.Add(5,"Clark");
            
            //Showing items
            for(int i=0;i<studentlist.Count;i++)
            {
            Console.WriteLine("Keys : "+studentlist.Keys[i]+"\tValues : "+ studentlist.Values[i]);
            }

            //Try to Insert Duplicate Keys
            try
            {
                studentlist.Add(5,"Mathew");
            }
            catch(ArgumentException ex)
            {
                Console.WriteLine("This key already exist. "+ex.ToString());
            }

            //Change Keys Values
            studentlist[1]="James Smith";

            //Search a Values
            if(studentlist.ContainsValue("Steven"))
            {
                Console.WriteLine("Items Found at Position : "+ studentlist.IndexOfValue("Steven"));
            }

            //Traverse using foreach
            foreach(KeyValuePair<int,string> k in studentlist)
            {
                Console.WriteLine("Key : {0} - Value : {1}",k.Key,k.Value);
            }            

            //Get the length of SortedList
            int len=studentlist.Count;
            Console.WriteLine("Length of StudentList is {0}",len.ToString());
        }
    }
}

Output

Keys : 1	Values : Jack
Keys : 2	Values : Mark
Keys : 3	Values : Neo
Keys : 4	Values : Steven
Keys : 5	Values : Clark

This key already exists. System.ArgumentException: An item with the same key has already been added. Key: 5
Parameter name: key
   at System.Collections.Generic.SortedList`2.Add(TKey key, TValue value)
   at SortedList_Example.Program.Main(String[] args) in /home/prashant/Documents/SEODocuments/CONTENT/Program/CSharp/GenericSortedList/Program.cs:line 27

Items Found at Position : 3

Key : 1 - Value : James Smith
Key : 2 - Value : Mark
Key : 3 - Value : Neo
Key : 4 - Value : Steven
Key : 5 - Value : Clark
Length of StudentList is 5
_

Summary

In this chapter you learned Generic SortedList<TKey, TValue> with complete programming example. In the next chapter you will learn Generic Queue<T> in C#.

 

Share your thought