C# SortedList (SortedList<TKey,TValue>)

In c#, SortedList is a generic type of collection and it is used to store a collection of key / value pairs that are sorted by key based on the associated IComparer<T> implementation.

 

By default, the sortedlist will sort a key / value pairs in ascending order of the key and the sortedlist will allow to store only the strongly typed objects i.e. the key / value pairs of specified data type.

 

In c#, the sortedlist will allow us to store a duplicate values but the keys must be unique and cannot be null to identify the values in sortedlist and the size of sortedlist will vary dynamically so we can add or remove an elements from the sortedlist based on our application requirements.

C# SortedList Declaration

In c#, sortedlist is a generic type of collection and it is provided by System.Collections.Generic namespace.

 

As discussed, collection is a class so to define a sortedlist, we must need to declare an instance of the sortedlist class before we perform any operations like add, delete, etc. like as shown below.

 

SortedList<TKey, TValue> slist = new SortedList<TKey, TValue>();

If you observe above sortedlist declaration, we created a generic sortedlist (slst) with an instance of sortedlist class using type parameters (TKey, TValue) as placeholders with an angle (<>) brackets.

 

Here, the angle (<>) brackets will indicate that the sortedlist is a generic type and type parameter TKey is to represent a type of keys to be accepted by sortedlist and TValue is used to represent a type of values to be accepted by sortedlist.

C# SortedList Initialization

Following is the example of initializing a generic sortedlist by specifying a required type for key and value.

 

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

If you observe above example, we defined a sortedlist (slist) with required key and value types to store. Here, the sortedlist will store a key of string type and value of int type.

 

Internally, the sortedlist will maintain a two object[] arrays, one for keys and another one for values so when we add key/value pair, it will perform a binary search using key to find an appropriate index to store a key and value in respective arrays.

C# SortedList Properties

Following are the some of commonly used properties of generic sortedlist in c# programming language.

 

PropertyDescription
Capacity It is used to get or set the number of elements a sortedlist can contain.
Count It is used to get the number of key/value pair elements in list.
Item[TKey] It is used get or set the value associated with the specified key.
Keys It is used get a collection of keys in sortedlist.
Values It is used get a collection of values in sortedlist.

C# SortedList Methods

Following are the some of commonly used methods of generic sortedlist to perform add, search, insert, delete or sort operations in c# programming language.

 

MethodDescription
Add It is used to add an elements with specified key and value in SortedList<TKey, TValue>.
Clear It will remove all the elements from SortedList<TKey, TValue>.
ContainsKey It is used determine whether the specified key exists in the SortedList<TKey, TValue> or not.
ContainsValue It is used determine whether the specified value exists in SortedList<TKey, TValue> or not.
IndexOfKey It is used to get the index value of specified key stored in the SortedList<TKey, TValue>.
IndexOfValue It is used to get the index value of specified value stored in the SortedList<TKey, TValue>.
Remove It is used to remove an element from SortedList<TKey, TValue> with specified key.
RemoveAt It is used to remove an element at the specified index position from SortedList<TKey, TValue>.
TryGetValue It is used to get the value associated with the specified key.

C# Add Elements to SortedList

In c#, while adding an elements to sortedlist we need to make sure that there will not be any duplicate keys because sortedlist will allow us to store a duplicate values but keys must be unique to identify the values in list.

 

Following is the example of adding a key/value pair elements to sorted list in different ways.

 

using System;

using System.Collections.Generic;

 

namespace Tutlane

{

    class Program

    {

        static void Main(string[] args)

        {

            //Create a new sorted list with int keys and string values.

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

            // Add elements to the list. No duplicate keys allowed but values can be duplicate

            slst.Add(1, "Suresh");

            slst.Add(4, "Rohini");

            slst.Add(2, "Trishi");

            slst.Add(3, null);

            // Another way to add elements. If key not exist, then that key adds a new key/value pair.

            slst[5] = "Trishi";

            // Add method throws exception if key already in the list

            try

            {

                slst.Add(2, "Praveen");

            }

            catch (ArgumentException)

            {

                Console.WriteLine("An element with Key = '2' already exists.");

            }        

            Console.WriteLine("*********List1 Elements********");

            // Accessing elements as KeyValuePair objects.

            foreach (KeyValuePair<int, string> item in slst)

            {

                Console.WriteLine("Key = {0}, Value = {1}", item.Key, item.Value);

            }

 

            // Creating and initializing list

            SortedList<string, int?> slst2 = new SortedList<string, int?> {

                                                {"msg2", 1},

                                                {"msg3", 20},

                                                {"msg4", 100},

                                                {"msg1", null}

                                            };

            Console.WriteLine("*********List2 Elements********");

            // Accessing elements as KeyValuePair objects.

            foreach (KeyValuePair<string, int?> item in slst2)

            {

                Console.WriteLine("Key = {0}, Value = {1}", item.Key, item.Value);

            }

            Console.ReadLine();

        }

    }

}

If you observe above example, we are able to define a new generic sortedlist (slst, slst2) collections by using System.Collections.Generic namespace. Here, we added only the defined data type keys and values to the newly created lists (slst, slst2) in different ways.

 

As discussed, Add method will throw an exception in case if we try to add a key (2) which is already existing so to handle that exception we used a try-catch block.

 

When we execute above c# program, we will get the result like as shown below.

 

C# Add Elements to SortedList Example Result

 

If you observe above result, by default all the list elements are sorted in ascending order based on the key and we got an exception when we tried to add a key (2) which is already existing and added a key (5) which is not existing in the list.

C# Access SortedList Elements

In c#, we have a different ways to access sorted list elements i.e. either by using index positions or by iterating through the list using for / foreach loops.

 

Following is the example of accessing the sortedlist elements in different ways.

 

using System;

using System.Collections.Generic;

 

namespace Tutlane

{

    class Program

    {

        static void Main(string[] args)

        {

            //Create a new sorted list

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

            slst.Add(1, "Suresh");

            slst.Add(4, "Rohini");

            slst.Add(2, "Trishi");

            slst.Add(3, "Praveen");

            // Access value with key

            string val1 = slst[2];

            // Access value with index position

            string val2 = slst.Values[2];

            // Access key with index position

            int val3 = slst.Keys[2];

            Console.WriteLine("******Access Elements with Key, Index Position*****");

            Console.WriteLine("Value at Key '2': " + val1);

            Console.WriteLine("Value at Index '2': " + val2);

            Console.WriteLine("Key at Index '2': " + val3);

            Console.WriteLine("*********Access Elements with Foreach Loop********");

            foreach (KeyValuePair<int, string> item in slst)

            {

                Console.WriteLine("Key = {0}, Value = {1}", item.Key, item.Value);

            }

            Console.WriteLine("*********Access Elements with For Loop********");

            for (int i = 0; i < slst.Count; i++)

            {

                Console.WriteLine("Key = {0}, Value = {1}", slst.Keys[i], slst.Values[0]);

            }

            Console.WriteLine("*********Sorted List Keys********");

            foreach (var item in slst.Keys)

            {

                Console.WriteLine("Key = {0}", item);

            }

            Console.WriteLine("*********Sorted List Values********");

            foreach (var item in slst.Values)

            {

                Console.WriteLine("Value = {0}", item);

            }

            Console.ReadLine();

        }

    }

}

If you observe above example, we are accessing generic list elements in different ways by using index positions, for and foreach loops based on our requirements.

 

When we execute above c# program, we will get the result like as shown below.

 

C# Access SortedList Elements Example Result

C# Remove Elements from SortedList

In c#, we have a different methods to remove an elements from the sorted list i.e. either by using Remove() or RemoveAt() methods.

 

Following is the example of deleting an elements from the sorted list in c# programming language.

 

using System;

using System.Collections.Generic;

 

namespace Tutlane

{

    class Program

    {

        static void Main(string[] args)

        {

            //Create a new sorted list

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

            slst.Add(1, "Suresh");

            slst.Add(4, "Rohini");

            slst.Add(2, "Trishi");

            slst.Add(3, "Praveen");

            slst.Add(5, "Sateesh");

            // Remove element with key 2

            slst.Remove(2);

            // Remove element at index position 2

            slst.RemoveAt(2);

            Console.WriteLine("*********Access Sorted List Elements********");

            Console.WriteLine();

            foreach (KeyValuePair<int, string> item in slst)

            {

                Console.WriteLine("Key = {0}, Value = {1}", item.Key, item.Value);

            }

            Console.ReadLine();

        }

    }

}

If you observe above example, we used a Remove() method to delete a particular key of element from the list and used a RemoveAt() method to delete an element at specified index position.

 

When we execute above c# program, we will get the result like as shown below.

 

C# Remove Elements from SortedList Example Result

 

In case, if you want to remove all the elements from sorted list, then use Clear() method.

C# SortedList Check If Item Exists

By using ContainsKey() and ContainsValue() methods, we can check whether the specified element exists in sorted list or not. In case, if it exists these methods will return true otherwise false.

 

Following is the example of using ContainsKey() and ContainsValue() methods to check for an item exists in sorted list or not in c#.

 

using System;

using System.Collections.Generic;

 

namespace Tutlane

{

    class Program

    {

        static void Main(string[] args)

        {

            //Create a new sorted list

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

            slst.Add(1, "Suresh");

            slst.Add(4, "Rohini");

            slst.Add(2, "Trishi");

            slst.Add(3, "Praveen");

            slst.Add(5, "Sateesh");

            Console.WriteLine("Contains Key 2: {0}", slst.ContainsKey(2));

            Console.WriteLine("Contains Value 'Tutlane': {0}", slst.ContainsValue("Tutlane"));

            Console.ReadLine();

        }

    }

}

If you observe above example, we used a ContainsKey() and ContainsValue() methods to check for a particular keys and values exists in sorted list (slst) or not.

 

When we execute above c# program, we will get the result like as shown below.

 

Contains Key 2: True

Contains Value 'Tutlane': False

C# SortedList (SortedList<TKey, TValue>) Overview

Following are important points which needs to remember about sorted list in c#.

 

  • SortedList is used to store a collection of key / value pairs that are sorted by key based on the associated IComparer<T> implementation.
  • SortedList will allow us to store a duplicate values but keys must be unique to identify the values in sorted list.
  • In SortedList, the keys cannot be null but the values can be null.
  • We can access SortedList elements either by using keys, index positions or with for and foreach loops. In foreach loop we need to use KeyValuePair<TKey, TValue> to get a key/value pairs from SortedList.
 
 

NEXT

C# Dictionary