YouTip LogoYouTip

Csharp Sortedlist

[![Image 1: C# Collections](#) C# Collections](#) In C#, a SortedList is a collection that automatically sorts elements by key. It stores data as key-value pairs and automatically sorts them in ascending order based on the key when adding or updating. The SortedList class represents a collection of key-value pairs sorted by key. These pairs can be accessed by both key and index. A SortedList is a combination of an array and a hash table. It contains a list of items that can be accessed using either a key or an index. If you access items by index, it acts like a dynamic array (ArrayList). If you access items by key, it acts like a hash table (Hashtable). The items in the collection are always sorted by key value. There are two versions of SortedList: 1. **Non-generic `SortedList`** (`System.Collections.SortedList`) 2. **Generic `SortedList`** (`System.Collections.Generic.SortedList`) **Features:** * **Automatic Sorting**: All keys are sorted in ascending order without needing to manually call a sort method. * **Key-Value Pair Storage**: Each key is unique, but the associated value can be duplicated. * **Dynamic Capacity Adjustment**: Automatically adjusts the internal storage size as needed. * **Index Access**: Data can be accessed via key or index. * **Efficient Operations**: Average time complexity for retrieval, insertion, and deletion is O(log n). The following table lists some common **properties** of the **SortedList** class: | Property Name | Type | Description | | --- | --- | --- | | `Count` | `int` | Gets the number of key-value pairs in the sorted list. | | `Capacity` | `int` | Gets or sets the capacity of the sorted list. | | `Comparer` | `IComparer` or `IComparer` | Gets the comparer used to sort the keys. | | `IsReadOnly` | `bool` | Indicates whether the sorted list is read-only. | | `IsFixedSize` | `bool` | Indicates whether the sorted list has a fixed size (always `false`). | | `Keys` | `ICollection` or `IList` | Gets all the keys in the sorted list. | | `Values` | `ICollection` or `IList` | Gets all the values in the sorted list. | The following table lists some common **methods** of the **SortedList** class: | Method Name | Return Type | Description | | --- | --- | --- | | **Add & Remove** | | | | `Add(TKey key, TValue value)` | `void` | Adds the specified key-value pair to the sorted list. | | `Remove(TKey key)` | `bool` | Removes the element with the specified key from the sorted list. | | `RemoveAt(int index)` | `void` | Removes the key-value pair at the specified index from the sorted list. | | `Clear()` | `void` | Removes all elements from the sorted list. | | **Find & Access** | | | | `ContainsKey(TKey key)` | `bool` | Determines whether the sorted list contains the specified key. | | `ContainsValue(TValue value)` | `bool` | Determines whether the sorted list contains the specified value. | | `IndexOfKey(TKey key)` | `int` | Returns the index of the specified key. | | `IndexOfValue(TValue value)` | `int` | Returns the index of the specified value. | | `TryGetValue(TKey key, out TValue value)` | `bool` | Gets the value associated with the specified key, returning `true` if found. | | **Copy & Enumerate** | | | | `CopyTo(Array array, int index)` | `void` | Copies the elements of the sorted list to an array, starting at the specified index. | | `GetEnumerator()` | `IEnumerator` | Returns an enumerator that iterates through the sorted list. | The following examples demonstrate the concept of SortedList. **Non-generic version operations:** ## Example using System; using System.Collections; namespace CollectionsApplication { class Program { static void Main(string[] args) { SortedList sl =new SortedList(); sl.Add("001", "Zara Ali"); sl.Add("002", "Abida Rehman"); sl.Add("003", "Joe Holzner"); sl.Add("004", "Mausam Benazir Nur"); sl.Add("005", "M. Amlan"); sl.Add("006", "M. Arif"); sl.Add("007", "Ritesh Saikia"); if(sl.ContainsValue("Nuha Ali")) { Console.WriteLine("This student name is already in the list"); } else { sl.Add("008", "Nuha Ali"); } // Get the collection of keys ICollection key = sl.Keys; foreach(string k in key) { Console.WriteLine(k +": "+ sl); } } } } When the above code is compiled and executed, it produces the following result: 001: Zara Ali002: Abida Rehman003: Joe Holzner004: Mausam Banazir Nur005: M. Amlan 006: M. Arif007: Ritesh Saikia008: Nuha Ali **Generic version:** ## Example using System; using System.Collections.Generic; class Program { static void Main() { // Create a generic SortedList SortedList sortedList =new SortedList(); // Add key-value pairs sortedList.Add(2, "Banana"); sortedList.Add(1, "Apple"); sortedList.Add(3, "Cherry"); // Automatically sorted by key Console.WriteLine("SortedList contents:"); foreach(var kvp in sortedList) { Console.WriteLine($"Key: {kvp.Key}, Value: {kvp.Value}"); } // Find and access Console.WriteLine($"n Value for key 2: {sortedList}");// Output: Banana // Remove an element sortedList.Remove(1); Console.WriteLine("n After removing key 1:"); foreach(var kvp in sortedList) { Console.WriteLine($"Key: {kvp.Key}, Value: {kvp.Value}"); } // Check key and value Console.WriteLine($"n Contains key 3: {sortedList.ContainsKey(3)}");// Output: True Console.WriteLine($"Contains value 'Apple': {sortedList.ContainsValue("Apple")}");// Output: False } } [![Image 2: C# Collections](#) C# Collections](#)
← Csharp StackCsharp Hashtable β†’