Non-Generic SortedList in C#

Non-Generic SortedList Collection Class in C# with Examples

In this article, I am going to discuss the Non-Generic SortedList Collection Class in C# with Examples. Please read our previous article where we discussed the Non-Generic Queue Collection Class in C# with Examples. At the end of this article, you will understand the following pointers with examples.

  1. What is SortedList in C#?
  2. Methods, Properties, and Constructor of Non-Generic SortedList Collection Class in C#
  3. How to Create a SortedList in C#?
  4. How to Add Elements into a SortedList in C#?
  5. How to access a SortedList in C#?
  6. How to Remove Elements from a SortedList in C#?
  7. How to check the availability of key/value pairs in a SortedList in C#?
  8. How to Clone the Non-Generic SortedList in C#?
  9. What is the use of the CopyTo method of Non-Generic SortedList Collection Class in C#?
  10. When to Use Non-Generic SortedList Collection in C#?
What is SortedList in C#?

The Non-Generic SortedList Collection Class in C# represents a collection of key/value pairs that are sorted by the keys and are accessible by key and by index. By default, it sorts the key/value pairs in ascending order. Non-Generic SortedList class belongs to System.Collections namespace.

Properties of Non-Generic SortedList Class in C#:
  1. The Non-Generic SortedList Class in C# implements the IEnumerable, ICollection, IDictionary, and ICloneable interfaces.
  2. We can access the element by its key or by its index in SortedList.
  3. The Non-Generic SortedList object internally maintains two arrays to store the elements of the list, i.e, one array for the keys and another array for the associated values. Here, the key cannot be null, but the value can be null. And one more, it does not allow duplicate keys.
  4. The capacity of the Non-Generic SortedList object is the number of key/value pairs it holds.
  5. In the Non-Generic SortedList object in C#, we can store values of the same type and of the different types as it operates on the object data type.
  6. In the same SortedList, it is not possible to store keys of different data types. If you try then the compiler will throw an exception.
Methods, Properties, and Constructor of Non-Generic SortedList Collection Class in C#:

If you go to the definition of Non-Generic SortedList Collection Class, then you will see the following. As you can see the SortedList Collection Class implements the Ithe IEnumerable, ICollection, IDictionary, and ICloneable interfaces. 

Methods, Properties, and Constructor of Non-Generic SortedList Collection Class in C#

How to Create a SortedList in C#?

The Non-Generic Collection SortedList class in C# privided six constructors that we can use to create an instance of SortedList. They are as follows:

  1. SortedList(): It initializes a new instance of the System.Collections.SortedList class that is empty, has the default initial capacity and is sorted according to the IComparable interface implemented by each key added to the System.Collections.SortedList object.
  2. SortedList(IComparer comparer): It initializes a new instance of the System.Collections.SortedList class that is empty, has the default initial capacity and is sorted according to the specified IComparer interface. The Parameter comparer specifies the System.Collections.IComparer implementation to use when comparing keys. -or- null to use the System.IComparable implementation of each key.
  3. SortedList(IDictionary d): IT initializes a new instance of the System.Collections.SortedList class that contains elements copied from the specified dictionary, has the same initial capacity as the number of elements copied and is sorted according to the System.IComparable interface implemented by each key. The Parameter d specifies the System.Collections.IDictionary implementation to copy to a new System.Collections.SortedList object.
  4. SortedList(int initialCapacity): It initializes a new instance of the System.Collections.SortedList class that is empty, has the specified initial capacity and is sorted according to the System.IComparable interface implemented by each key added to the System.Collections.SortedList object. The Parameter initialCapacity specifies the initial number of elements that the System.Collections.SortedList object can contain.
  5. SortedList(IComparer comparer, int capacity): It initializes a new instance of the System.Collections.SortedList class that is empty, has the specified initial capacity and is sorted according to the specified System.Collections.IComparer interface. The Parameter comparer specifies the System.Collections.IComparer implementation to use when comparing keys. -or- null to use the System.IComparable implementation of each key. The Parameter capacity specifies the initial number of elements that the System.Collections.SortedList object can contain.
  6. SortedList(IDictionary d, IComparer comparer): It initializes a new instance of the System.Collections.SortedList class that contains elements copied from the specified dictionary, has the same initial capacity as the number of elements copied and is sorted according to the specified System.Collections.IComparer interface. The Parameter d specifies the System.Collections.IDictionary implementation to copy to a new System.Collections.SortedList object. The Parameter comparer specifies the System.Collections.IComparer implementation to use when comparing keys. -or- null to use the System.IComparable implementation of each key.

Let’s see how to create a SortedList using the SortedList constructor in C#:

Step1:
As the SortedList class belongs to System.Collections namespace, so first, we need to import the System.Collections namespace into our program as follows:
using System.Collections;

Step2:
Next, we need to create an instance of the SortedList class using the SortedList () constructor as follows:
SortedList sortedList = new SortedList();

How to Add Elements into a SortedList in C#?

If you want to add a key/value pair to a SortedList, then you need to use the Add() method of the SortedList class.

Add(object key, object value): The Add(object key, object value) method is used to add an element with the specified key and value to a SortedList. Here, the parameter key specifies the key of the element to add and the parameter value specifies the element to add. The value can be null.
SortedList sortedList = new SortedList();
sortedList.Add(1, “One”);
sortedList.Add(3, “Three”);

You can also store a key/value pair in the SortedList using Collection Initializer as follows.
SortedList sortedList = new SortedList
{
       { 1, “One” },
       { 3, “Three” }
};

How to access a SortedList in C#?

We can access the key/value pairs of the SortedList in C# using three different ways. They are as follows:

Using for loop to access SortedList in C#:
You can use for loop in C# to access the key/value pairs of the SortedList as shown below.
for (int x = 0; x < sortedList.Count; x++)
{
      Console.WriteLine($”Key: {sortedList.GetKey(x)}, Value: {sortedList.GetByIndex(x)}”);
}

Using Index to access SortedList in C#:
You can access the individual value of the SortedList in C# by using the index. In this case, we need to pass the key or index as a parameter to find the respective value. If the specified key is not present, then the compiler will throw an exception. The syntax is given below.
Console.WriteLine($”Value at Index 1 is:{sortedList[1]}”);
string val = (string)sortedList[1];
Console.WriteLine(val);

Using foreach loop to access SortedList in C#:
We can also use a for-each loop to access the key/value pairs of the SortedList in C# as follows.
foreach (DictionaryEntry item in sortedList)
{
        Console.WriteLine($”Key: {item.Key}, Value: {item.Value}”);
}

Example to Understand How to Create a SortedList and Add Elements in C#:

For a better understanding of how to create a SortedList and how to add elements to a SortedList in C#, and how to access the elements, please have a look at the below example.

using System;
using System.Collections;
namespace NonGenericCollections
{
    public class SortedListDemo
    {
        public static void Main(string[] args)
        {
            //Creating sortedList object
            SortedList sortedList = new SortedList();

            //Adding Elements to SortedList using Add
            sortedList.Add(1, "One");
            sortedList.Add(5, "Five");
            sortedList.Add(4, "Four");
            sortedList.Add(2, "Two");
            sortedList.Add(3, "Three");

            //Duplicate Key not allowed
            //System.ArgumentException: 'Item has already been added. Key in dictionary: '4'  Key being added: '4''
            //sortedList.Add(4, "Four");

            //Accessing SortedList using For loop
            Console.WriteLine("Accessing SortedList using For loop");
            for (int x = 0; x < sortedList.Count; x++)
            {
                Console.WriteLine($"Key: {sortedList.GetKey(x)}, Value: {sortedList.GetByIndex(x)}");
            }

            Console.WriteLine("\nAccessing SortedList using For Each loop");
            //Accessing SortedList using For Each loop
            foreach (DictionaryEntry item in sortedList)
            {
                Console.WriteLine($"Key: {item.Key}, Value: {item.Value}");
            }

            Console.WriteLine("\nAccessing SortedList using Index");
            Console.WriteLine($"Key: 1, Value: {sortedList[1]}");
            Console.WriteLine($"Key: 2, Value: {sortedList[2]}");
            Console.WriteLine($"Key: 3, Value: {sortedList[3]}");

            Console.ReadKey();
        }
    }
}
Output:

Example to Understand How to Create a SortedList and Add Elements in C#

Please note here we are getting the output based on the ascending order of the keys.

Adding Elements to SortedList Example using Collection Initializer in C#:

In the below example, we are using Collection Initializer syntax instead of the Add method to add key-value pairs into the sorted list in C#.

using System;
using System.Collections;
namespace NonGenericCollections
{
    public class SortedListDemo
    {
        public static void Main(string[] args)
        {
            //Creating sortedList using Object Initializer
            SortedList sortedList = new SortedList
            {
                { "Ind", "India" },
                { "USA", "United State of America" },
                { "SA", "South Africa" },
                { "PAK", "Pakistan" }
            };

            Console.WriteLine("SortedList Elements");
            foreach (DictionaryEntry item in sortedList)
            {
                Console.WriteLine($"Key: {item.Key}, Value: {item.Value}");
            }

            Console.ReadKey();
        }
    }
}
Output:

Adding Elements to SortedList Example using Collection Initializer in C#

How to Remove Elements from a SortedList in C#?

The Non_Generic SortedList Collection Class in C# provides the following methods to remove elements from SortedList.

  1. Remove(object key): This method is used to remove the element with the specified key from a System.Collections.SortedList object. The parameter key specifies the element to remove.
  2. RemoveAt(int index): This method is used to remove the element at the specified index of a System.Collections.SortedList object. The parameter index specifies the element to remove. It is 0 based Index.
  3. Clear(): This method is used to remove all elements from a System.Collections.SortedList object.

Let us see an example to understand the above methods of SortedList Collection Class in C#. Please have a look at the below example.’

using System;
using System.Collections;
namespace NonGenericCollections
{
    public class SortedListDemo
    {
        public static void Main(string[] args)
        {
            //Creating sortedList object
            SortedList sortedList = new SortedList();

            //Adding Elements to SortedList using Add
            sortedList.Add("Ind", "India");
            sortedList.Add("USA", "United State of America");
            sortedList.Add("SA", "South Africa");
            sortedList.Add("PAK", "Pakistan");

            Console.WriteLine("SortedList Elements");
            foreach (DictionaryEntry item in sortedList)
            {
                Console.WriteLine($"Key: {item.Key}, Value: {item.Value}");
            }

            // Remove value having key PAK Using Remove() method
            sortedList.Remove("PAK");

            // After Remove() method
            Console.WriteLine("\nSortedList Elements After Remove Method");
            foreach (DictionaryEntry item in sortedList)
            {
                Console.WriteLine($"Key: {item.Key}, Value: {item.Value}");
            }

            // Remove element at index 1 Using RemoveAt() method
            sortedList.RemoveAt(1);
            Console.WriteLine("\nSortedList Elements After RemoveAT Method");
            foreach (DictionaryEntry item in sortedList)
            {
                Console.WriteLine($"Key: {item.Key}, Value: {item.Value}");
            }

            // Remove all key/value pairs Using Clear method
            sortedList.Clear();
            Console.WriteLine($"After Clear Method Total Key-Value Pair Present is : {sortedList.Count} ");
            Console.ReadKey();
        }
    }
}
Output:

How to Remove Elements from a SortedList in C#?

How to check the availability of key/value pairs in a SortedList in C#?

If you want to check whether the key/value pair exists or not in the SortedList, then you can use the following methods of the SortedList class.

  1. Contains(object key): This method is used to determine whether the SortedList object contains a specific key. The parameter key to locating in the SortedList object. It returns true if the SortedList object contains an element with the specified key; otherwise, false. If the key is null, then it will throw System.ArgumentNullException.
  2. ContainsKey(object key): This method is used to determine whether a SortedList object contains a specific key. The parameter key to locating in the SortedList object. It returns true if the SortedList object contains an element with the specified key; otherwise, false. If the key is null, then it will throw System.ArgumentNullException.
  3. ContainsValue(object value): This method is used to determine whether a System.Collections.SortedList object contains a specific value. The parameter value to locate in the SortedList object. The value can be null. It returns true if the SortedList object contains an element with the specified value; otherwise, false.

Let us understand this with an example. The following example shows how to use the Contains, ContainsKey, and ContainsValue method of the non-generic SortedList collection class in C#.

using System;
using System.Collections;
namespace NonGenericCollections
{
    public class SortedListDemo
    {
        public static void Main(string[] args)
        {
            //Creating sortedList using Object Initializer
            SortedList sortedList = new SortedList
            {
                { "Ind", "India" },
                { "USA", "United State of America" },
                { "SA", "South Africa" },
                { "PAK", "Pakistan" }
            };

            //Checking the key using the Contains methid
            Console.WriteLine("Is Ind Key Exists : " + sortedList.Contains("Ind"));
            Console.WriteLine("Is NZ Key Exists : " + sortedList.Contains("NZ"));

            //Checking the key using the ContainsKey methid
            Console.WriteLine("Is Ind Key Exists : " + sortedList.ContainsKey("Ind"));
            Console.WriteLine("Is NZ Key Exists : " + sortedList.ContainsKey("NZ"));

            //Checking the value using the ContainsValue method
            Console.WriteLine("Is India value Exists : " + sortedList.ContainsValue("India"));
            Console.WriteLine("Is Bangladesh value Exists : " + sortedList.ContainsValue("Bangladesh"));

            Console.ReadKey();
        }
    }
}
Output:

blank

How to Clone the Non-Generic SortedList in C#?

If you want to clone or copy the Non-Generic SortedList in C#, then you need to use the following Clone() method provided by the SortedList Collection Class.

  1. Clone(): This method is used to create and return a shallow copy of a SortedList object.

For a better understanding, please have a look at the below example.

using System;
using System.Collections;
namespace NonGenericCollections
{
    public class SortedListDemo
    {
        public static void Main(string[] args)
        {
            //Creating sortedList using Object Initializer
            SortedList sortedList = new SortedList
            {
                { "Ind", "India" },
                { "USA", "United State of America" },
                { "SA", "South Africa" },
                { "PAK", "Pakistan" }
            };

            Console.WriteLine("Sorted List Elements:");
            foreach (DictionaryEntry item in sortedList)
            {
                Console.WriteLine($"Key: {item.Key}, Value: {item.Value}");
            }

            Console.WriteLine("\nCloned Sorted List Elements:");
            //Creating a clone sortedList using Clone method
            SortedList cloneSortedList = (SortedList)sortedList.Clone();
            foreach (DictionaryEntry item in cloneSortedList)
            {
                Console.WriteLine($"Key: {item.Key}, Value: {item.Value}");
            }

            Console.ReadKey();
        }
    }
}
Output:

Non-Generic SortedList Collection Class in C# with Examples

What is the use of the CopyTo method of Non-Generic SortedList Collection Class in C#?

CopyTo(Array array, int arrayIndex): The CopyTo method of Non-Generic SortedList Collection Class in C# is used to copy SortedList elements to a one-dimensional Array object, starting at the specified index in the array. Here, the parameter array specifies the one-dimensional Array object that is the destination of the DictionaryEntry objects copied from SortedList. The Array must have zero-based indexing. The arrayIndex parameter specifies the zero-based index in the array at which copying begins. If the parameter array is null, then it will throw ArgumentNullException. If the parameter arrayIndex is less than zero, then it will throw ArgumentOutOfRangeException.

The key/value pairs are copied to the Array object in the same order in which the enumerator iterates through the SortedList object. This method is an O(n) operation, where n is Count.

  1. To copy only the keys in the SortedList, use SortedList.Keys.CopyTo.
  2. To copy only the values in the SortedList, use SortedList.Values.CopyTo.

For a better understanding, please have a look at the below example.

using System;
using System.Collections;

namespace NonGenericCollections
{
    public class SortedListDemo
    {
        public static void Main(string[] args)
        {
            //Creating sortedList using Object Initializer
            SortedList sortedList = new SortedList
            {
                { "Ind", "India" },
                { "USA", "United State of America" },
                { "SA", "South Africa" },
                { "PAK", "Pakistan" }
            };

            Console.WriteLine("Sorted List Elements:");
            foreach (DictionaryEntry item in sortedList)
            {
                Console.WriteLine($"Key: {item.Key} : Value: {item.Value}");
            }

            DictionaryEntry[] myTargetArray = new DictionaryEntry[5];
            sortedList.CopyTo(myTargetArray, 1);
            Console.WriteLine("\nCopyTo Method to Copy Keys and values:");
            for (int i = 0; i < myTargetArray.Length; i++)
            {
                Console.WriteLine($"{myTargetArray[i].Key} : {myTargetArray[i].Value}");
            }

            Object[] myObjArrayKey = new Object[5];
            Object[] myObjArrayValue = new Object[5];

            Console.WriteLine("\nCopyTo Method to Copy Keys:");
            sortedList.Keys.CopyTo(myObjArrayKey, 0);
            foreach (var key in myObjArrayKey)
            {
                Console.WriteLine($"{key} ");
            }

            Console.WriteLine("\nCopyTo Method to Copy Values:");
            sortedList.Values.CopyTo(myObjArrayValue, 1);
            foreach (var key in myObjArrayValue)
            {
                Console.WriteLine($"{key} ");
            }
            Console.ReadKey();
        }
    }
}
Output:

What is the use of the CopyTo method of Non-Generic SortedList Collection Class in C#?

Non-Generic SortedList Collection Class Properties in C#
  1. Keys: Gets the keys in a System.Collections.SortedList object. It returns a System.Collections.ICollection object containing the keys in the System.Collections.SortedList object.
  2. IsSynchronized: Gets a value indicating whether access to a SortedList object is synchronized (thread-safe). It returns true if access to the SortedList object is synchronized (thread-safe); otherwise, false. The default is false.
  3. IsReadOnly: Gets a value indicating whether the SortedList object is read-only. It returns true if the System.Collections.SortedList object is read-only; otherwise, false. The default is false.
  4. IsFixedSize: It returns true if the SortedList object has a fixed size; otherwise, false. The default is false.
  5. Count: It returns the number of elements contained in the System.Collections.SortedList object.
  6. Capacity: It returns the number of elements that the System.Collections.SortedList object can contain.
  7. SyncRoot: It returns an object that can be used to synchronize access to the System.Collections.SortedList object.
  8. Values: Gets the values in a SortedList object. It returns a System.Collections.ICollection object containing the values in the System.Collections.SortedList object.
When to Use Non-Generic SortedList Collection in C#?

The Non-Generic SortedList Collection is a powerful tool for performing quick manipulation of key-value data in an orderly manner. But there are certain scenarios where this class may not be suitable. For example, by its nature, a SortedList must always be sorted. Therefore, whenever we add a new key-value pair to the list or remove a key-value pair from the SortedList, then it must sort itself to ensure that all elements are in the right order. This becomes more expensive as we increase the number of elements in our SortedList.

We should only use SortedList when we want to handle smaller collections that need to be sorted at all times. When dealing with larger collections, it is more efficient to use a dictionary, HashSet, or even a regular list which we can then sort once at the point where we need it.

In the next article, I am going to discuss the Advantages and Disadvantages of Non-Generic Collection Classes in C# with Examples. Here, in this article, I try to explain the Non-Generic Collection SortedList Class in C# with Examples. I hope this Non-Generic SortedList Collection Class in C# with Examples article will help you with your needs. I would like to have your feedback. Please post your feedback, question, or comments about this article.

1 thought on “Non-Generic SortedList in C#”

  1. blank

    Guys,
    Please give your valuable feedback. And also, give your suggestions about the Non-Generic SortedList Collection Class concept. If you have any better examples, you can also put them in the comment section. If you have any key points related to the Non-Generic SortedList Collection Class in C#, you can also share the same.

Leave a Reply

Your email address will not be published.