C sorted list LEARNOVITA

C# Sorted List Tutorial with Examples | Learn in 1 Day FREE

Last updated on 16th Aug 2022, Blog, Tutorials

About author

Manobala (C# Automation Tester )

Manobala is a C# Automation Tester and he has tons of experience in the areas of HTTP, SOAP/REST, VisualStudio, TFS, etc., CI/CD, functional, regression, and .NET technology stack. he spends most of his time researching technology, and startups.

(5.0) | 18987 Ratings 2181

Introduction of C# SortedList :

A SortedList object internally manages two arrays to save the elements of the list; that is, one array for the keys and another array for the associated values. Every element is a key/value pair that can be accessed as a DictionaryEntry object. A key cannot be null, but the value can be. The capacity of a SortedList object is the number of elements SortedList can hold. As elements are added to the SortedList, the capacity is automatically increased as needed through reallocation. The capacity can be decreased by calling the TrimToSize or by setting the Capacity property explicitly.

C# SortedList

NET Framework only: For very large SortedList objects, can increase the maximum capacity to 2 billion elements on a 64-bit system by setting the enabled attribute of the <"gcAllowVeryLargeObjects"> configuration element to true in the run-time environment. The elements of a SortedList object are sorted by the keys either according to a specific IComparer implementation specified when the SortedList is generated or according to the IComparable implementation provided by the keys themselves.

In either case, a SortedList does not allow the duplicate keys. The index sequence is based on a sort sequence. When an element is added, it is inserted into the SortedList in the correct sort order, and indexing adjusts accordingly. When an element is removed, the indexing also adjusts accordingly. Therefore, the index of a specific key/value pair might modify as elements are added or removed from the SortedList object. Operations on a SortedList object to be slower than operations on a Hashtable object because of the sorting.

The SortedList offers high flexibility by allowing access to the values either through the associated keys or through the indexes. Elements in this collection can be accessed by using an integer index. Indexes in this collection are zero-based. The for each statement of the C# language returns an object of the kind of the elements in the collection. Each element of the SortedList object is a key/value pair, the element type is not the type of the key or the type of the value. Rather, the element type is DictionaryEntry.

For example:

  • C#
  • foreach (DictionaryEntry de in mySortedList)
  • {
  • //…
  • }

The foreach statement is a wrapper around the enumerator, which permits only reading from, not writing to, the collection.

Creating a SortedList:

The following example demonstrates how to make a generic SortedList<"TKey, TValue">, and add key-value pairs in it.

Example: Create a SortedList and Add Elements

  • //SortedList of int keys, string values
  • SortedList<"int, string"> numberNames = new SortedList<"int, string">();
  • numberNames.Add(3, “Three”);
  • numberNames.Add(1, “One”);
  • numberNames.Add(2, “Two”);
  • numberNames.Add(4, null);
  • numberNames.Add(10, “Ten”);
  • numberNames.Add(5, “Five”);
  • //The following will throw exceptions
  • //numberNames.Add(“Three”, 3); //Compile-time error: key must be int type
  • //numberNames.Add(1, “One”); //Run-time exception: duplicate key
  • //numberNames.Add(null, “Five”);//Run-time exception: key cannot be null

Accessing SortedList:

Specify a key in the indexer sortedList[key], to get or set the value in a SortedList.

Remove Elements from SortedList:

Use the Remove(key) and RemoveAt(index) methods to remove key-value pairs from the SortedList.

Constructors:

    SortedList() Initializes a new instance of the SortedList class that is empty, has default initial capacity, and is sorted according to the IComparable interface implemented by every key added to the SortedList object.
    SortedList(IComparer) Initializes a new instance of the SortedList class that is empty, has the default initial capacity, and is sorted according to the particular IComparer interface.
    SortedList(IComparer, Int32) Initializes a new instance of the SortedList class that is empty, has the specified initial capacity, and is sorted according to the particular IComparer interface.
    SortedList(IDictionary) Initializes a new instance of the SortedList class that includes elements copied from the specified dictionary, has the same initial capacity as the number of elements copied, and is sorted according to the IComparable interface implemented by every key.
    SortedList(IDictionary, IComparer) Initializes a new instance of the SortedList class that includes elements copied from the particular dictionary, has the same initial capacity as the number of elements copied, and is sorted according to the specified IComparer interface.
    SortedList(Int32) Initializes a new instance of the SortedList class that is empty, has the particular initial capacity, and is sorted according to the IComparable interface implemented by every key added to the SortedList object.

Properties:

    Capacity Gets or sets a capacity of the SortedList object.
    Count Gets the number of elements included in a SortedList object.
    IsFixedSize Gets a value denoting whether a SortedList object has a fixed size.
    IsReadOnly Gets a value denoting whether a SortedList object is read-only.
    IsSynchronized Gets a value denoting whether access to a SortedList object is synchronized (thread safe).
    Item[Object] Gets or sets the value associated with a specific key in the SortedList object.
    Keys Gets the keys in a SortedList object.
    SyncRoot Gets an object that can be used to synchronize access to the SortedList object.
    Values Gets the values in the SortedList object.

Methods

    Add(Object, Object) Adds an element with the particular key and value to a SortedList object.
    Clear() Removes all the elements from a SortedList object.
    Clone() Creates a shallow copy of the SortedList object.
    Contains(Object) Determines whether a SortedList object includes a specific key.
    ContainsKey(Object) Find whether a SortedList object contains a specific key.
    ContainsValue(Object) Find whether a SortedList object contains a specific value.
    CopyTo(Array, Int32) Copies SortedList elements to a one-dimensional Array object, starting at the particular index in the array.
    Equals(Object) Find whether the specified object is equal to the current object. (Inherited from Object)
    GetByIndex(Int32) Gets the value at the particular index of a SortedList object.
    GetEnumerator() Returns an IDictionaryEnumerator object that iterates through a SortedList object.
    GetHashCode() Serves as a default hash function.
    GetKey(Int32) Gets the key at the particular index of a SortedList object.
    GetKeyList() Gets the keys in the SortedList object.
    GetType() Gets the Type of a current instance. (Inherited from Object)
    GetValueList() Gets values in the SortedList object.
    IndexOfKey(Object) Returns the zero-based index of the particular key in a SortedList object.
    IndexOfValue(Object) Returns the zero-based index of a first occurrence of the particular value in a SortedList object.
    MemberwiseClone() Generate a shallow copy of the current Object. (Inherited from Object)
    Remove(Object) Removes the element with the particular key from a SortedList object.
    RemoveAt(Int32) Removes the element at the particular index of a SortedList object.
    SetByIndex(Int32, Object) Replaces the value at a particular index in a SortedList object.
    Synchronized(SortedList) Returns a synchronized wrapper for the SortedList object.
    ToString() Returns a string that represents a current object. (Inherited from Object)
    TrimToSize() Sets a capacity to the actual number of elements in the SortedList object.

C# – SortedList<"TKey, TValue">

The SortedList<"TKey, TValue">, and SortedList are a collection of classes that can save key-value pairs that are sorted by the keys based on the associated IComparer implementation. For example, if the keys are primitive types, then sorted in ascending order of keys. C# encourages generic and non-generic SortedList. It is recommended to use generic SortedList<"TKey, TValue"> because it performs faster and less error-prone than the non-generic SortedList.

SortedList Characteristics:

  • SortedList<"TKey, TValue"> is an array of key-value pairs sorted by the keys.
  • Sorts primitive type keys in ascending order and object keys based on IComparer<"T">.
  • Comes under the System.Collection.Generic namespace.
  • A key must be unique and cannot be null.
  • A value can null or duplicate.
  • A value can accessed by passing associated key in indexer mySortedList[key]
  • Contains elements of the type KeyValuePair<"TKey, TValue">
  • It uses less memory than the SortedDictionary<"TKey,TValue">.
  • It is faster in retrieval of data once sorted, whereas SortedDictionary<"TKey, TValue"> is faster in insertion and removing the key-value pairs.

Are you looking training with Right Jobs?

Contact Us

Popular Courses