In the C# programming language, the SortedList<TKey, TValue> is an array of key/value pairs. It stores values on the basis of a key. The SortedList<TKey, TValue> class contains unique keys and maintains ascending order on the basis of key. With the help of the key, we can easily search or remove elements. It is found in System.Collections.Generic namespace. It is like the SortedDictionary<TKey, TValue> class.
Syntax
It has the following syntax.
SortedList<TKey, TValue> variable_name = new SortedList<TKey, TValue>();
SortedList<TKey, TValue> variable_name = new SortedList<TKey, TValue>
{
{ key1, value1 },
{ key2, value2 },
{ key3, value3 }
};
In this example,
- TKey: It is used to represent the type of keys in the sorted list.
- Tvalue: It is used to represent the type of value in the sorted list.
- SortedList<TKey, TValue>: It is used to represent a generic class that is used to store the unique keys and values in ascending order of the keys.
C# Simple Example for SortedList
Let's consider a scenario to demonstrate the implementation of SortedList in C++.
Example
using System;
using System.Collections.Generic;
class C# Tutorial
{
static void Main()
{
// Here, we have created a SortedList of string keys and int values
SortedList<string, int> marks = new SortedList<string, int>
{
{ "C++", 85 },
{ "Java", 90 },
{ "Python", 95 }
};
foreach (KeyValuePair<string, int> kvp in marks)
{
Console.WriteLine($"{kvp.Key}: {kvp.Value}");
}
}
}
Output:
C++: 85
Java: 90
Python: 95
Explanation:
In this instance, a SortedList has been established featuring string keys denoting various programming languages and integer values representing scores. Subsequently, the SortedList function has been employed to automatically arrange the items based on key in an ascending manner, while the foreach loop navigates through each key-value combination to exhibit them in a sorted sequence.
Key Features of the SortedList
Some of the primary characteristics of the SortedList in C# include:
There are several features of the SortedList Function in C#. Some of them are as follows:
- In C#, every key in the SortedList should be unique and cannot be null. However, the SortedList values can be duplicates or null.
- It is useful to implement several interfaces, including IDictionary<TKey, TValue>, ICollection<KeyValuePair<TKey, TValue>>, IEnumerable<KeyValuePair<TKey, TValue>>, and read-only methods.
- It is used to store as key-value pairs in order of ascending keys, with an array-based data structure.
- It provides fast retrieval by key or by index, but slower insertions and deletions than some collections, such as SortedDictionary<TKey, TValue>.
- It supports fast memory usage and direct access to the value/index, particularly when the keys are not frequently changing.
- It is used to sort its keys in ascending order by default using the IComparer<TKey> interface. We can also provide a custom comparer to define a different sorting order, such as descending or case-insensitive sorting.
Common Operations
There are numerous standard functions of SortedList in C#. Some primary actions in C# include:
- Adding
In C# programming, it is possible to add a new key-value pair to a SortedList. The key needs to be both unique and non-null. Any attempt to add a duplicate key or a null key will result in an exception being thrown. While values can be null or duplicated based on the type settings, the key must remain unique. When adding a new pair, the SortedList automatically inserts it into the correct sorted position based on the key.
C# Add Operation using the SortedList
Let's consider a scenario to demonstrate the process of inserting elements using the SortedList data structure in the C# programming language.
Example
using System;
using System.Collections.Generic;
class Example_Add
{
static void Main()
{
SortedList<string, int> marks = new SortedList<string, int>();
marks.Add("C++", 90);
marks.Add("Python", 85);
Console.WriteLine("Added successfully.");
}
}
Output:
Added successfully.
Explanation:
In this instance, a SortedList was generated with subject names as keys and corresponding marks as values. The list currently includes two items: C++ with a score of 90 and Python with 85. The sorting feature organizes the keys alphabetically by default. Upon inputting the data, a confirmation message "Added successfully" is shown to indicate the completion of the process.
- Remove
In C# programming, it is possible to remove the item associated with a specified key from the SortedList data structure. If the key is not present, no changes are made. This operation may trigger the rearrangement of elements within the array to maintain the sorted order.
C# SortedList Example for Remove Operation
Let's consider an example to demonstrate the delete operation using the SortedList in C#.
Example
using System;
using System.Collections.Generic;
class Example_Remove
{
static void Main()
{
SortedList<string, int> marks = new SortedList<string, int> { { "C++", 90 }, { "Java", 85 } };
marks.Remove("C++");
Console.WriteLine("C++ removed.");
}
}
Output:
C++ removed.
Explanation:
In this illustration, a SortedList has been established featuring two topics along with their corresponding grades. Following this, the entry linked to the key C++ is removed from the list. A notification is then displayed to confirm the successful deletion of the C++ entry.
- ContainsKey
In C#, this method checks if the SortedList includes a key element. It returns true if the specified key exists; otherwise, it returns false. This function provides a quick search functionality using the sorted keys.
C# SortedList Example for ContainsKey Operation
Let's consider an instance to demonstrate the ContainsKey function using the SortedList data structure in the C# programming language.
Example
using System;
using System.Collections.Generic;
class Example_ContainsKey
{
static void Main()
{
SortedList<int, string> students = new SortedList<int, string>();
students.Add(101, "Riya");
students.Add(102, "Aman");
if (students.ContainsKey(103))
Console.WriteLine("Student with ID 103 exists.");
else
Console.WriteLine("Student with ID 103 not found.");
}
}
Output:
Student with ID 103 not found.
Explanation:
In this instance, a SortedList has been established where student IDs act as keys and names are kept as values. Two students with IDs 101 and 102 are added to the list. Subsequently, a search is conducted for the key 103. Since it is not present, the system displays a message stating "Student with ID 103 not found."
- ContainsValue
This function verifies if the SortedList includes at least one item with the given value. The search process is linear due to the unsorted nature of the values within the list.
C# SortedList Example for ContainsValue Operation
Let's consider a scenario to demonstrate the ContainsValue functionality using the SortedList in C#.
Example
using System;
using System.Collections.Generic;
class Example_ContainsValue
{
static void Main()
{
SortedList<string, double> products = new SortedList<string, double>
{
{ "Laptop", 50000 },
{ "Mobile", 20000 },
{ "Tablet", 15000 }
};
double price = 20000;
if (products.ContainsValue(price))
Console.WriteLine("A product with price " + price + " is available.");
else
Console.WriteLine("No product with price " + price + " found.");
}
}
Output:
A product with price 20000 is available.
Explanation:
In this instance, we create a SortedList where the names of products act as keys, and their respective prices function as values. It checks if any product is priced at 20000. As the Mobile item has this price, the system displays A product with a 20000 price tag is in stock.
In C#, the Keys property retrieves the set of keys within the SortedList, arranged in ascending order. This collection maintains the sequence of the sorted keys and can be enumerated.
C# SortedList Example for Keys Operation
Let's consider a scenario to demonstrate the process of performing the Keys operation with the SortedList in C#.
Example
using System;
using System.Collections.Generic;
class Example_Keys
{
static void Main()
{
SortedList<string, string> countries = new SortedList<string, string>
{
{ "US", "United States" },
{ "IN", "India" },
{ "UK", "United Kingdom" },
{ "CA", "Canada" }
};
Console.WriteLine("Country codes in sorted order:");
foreach (string code in countries.Keys)
Console.WriteLine(code);
}
}
Output:
Country codes in sorted order:
CA
IN
UK
US
Explanation:
In this instance, we've established a SortedList containing country codes as keys and corresponding country names as values. We iterate through the Keys collection, which is inherently sorted, showcasing each country code in alphabetical order.
- Entries
In C# programming, the value represents a compilation of all elements within the SortedList sorted according to their respective keys. These values can be accessed either by their index or iterated through by key.
C# SortedList Example for Values
Let's consider a scenario to demonstrate the usage of values with the SortedList data structure in the C# programming language.
Example
using System;
using System.Collections.Generic;
class Example_Values
{
static void Main()
{
SortedList<string, string> country = new SortedList<string, string>
{
{ "US", "United States" },
{ "IN", "India" },
{ "UK", "United Kingdom" },
{ "CA", "Canada" }
};
Console.WriteLine("Countries in key-sorted order:");
foreach (string c in country.Values)
Console.WriteLine(c);
}
}
Output:
Countries in key-sorted order:
Canada
India
United Kingdom
United States
Explanation:
In this instance, we've established a SortedList where country codes serve as keys and corresponding country names as values. The keys are sorted in alphabetical order automatically. Subsequently, it iterates through the Values collection and displays the country names following the sorted keys sequence: Canada, India, United Kingdom, United States.
- Item[TKey]
In C#, the Item[TKey] serves as an indexer for accessing and modifying values associated with specific keys. When setting a value for a key that doesn't already exist, an exception is triggered. This functionality enables direct access to values based on their keys.
C# SortedList Example for Item[TKey]
Let's consider a scenario to demonstrate the Item[TKey] feature utilizing the SortedList in the C# programming language.
Example
using System;
using System.Collections.Generic;
class Example_Indexer
{
static void Main()
{
SortedList<string, int> marks = new SortedList<string, int>
{
{ "Math", 90 },
{ "Science", 85 },
{ "English", 80 }
};
Console.WriteLine("Marks in Science: " + marks["Science"]);
marks["Science"] = 95;
Console.WriteLine("Updated Marks in Science: " + marks["Science"]);
}
}
Output:
Marks in Science: 85
Updated Marks in Science: 95
Explanation:
In this instance, a SortedList has been established with subjects serving as keys and marks as corresponding values. Initially, the program displays the marks for the Science subject by utilizing the indexer. Subsequently, the value is updated to 95, and the revised marks are displayed.
- Count
In C# programming, the Count attribute is employed to retrieve the quantity of key-value pairs presently held in a SortedList<TKey, TValue>. This indicates the real elements in the collection, regardless of the allocated internal Capacity for storage.
C# SortedList Example for Count
Let's consider a scenario to demonstrate the process of counting elements using the SortedList data structure in C#.
Example
using System;
using System.Collections.Generic;
class Example_Count
{
static void Main()
{
SortedList<string, int> library = new SortedList<string, int>
{
{ "Harry Potter", 5 },
{ "The Hobbit", 3 },
{ "1984", 4 }
};
Console.WriteLine("Total books in library: " + library.Count);
}
}
Output:
Total books in library: 3
Explanation:
In this instance, a SortedList has been generated where the titles of books serve as keys and their respective frequencies as values. Subsequently, the total number of items in the list is showcased by utilizing the Count property, which stands at 3 in this case.
Difference between C# SortedList__PRESERVE_31__ and SortedDictionary__PRESERVE_32__
In the C# programming language, the SortedList<TKey, TValue> class uses less memory than SortedDictionary<TKey, TValue>. It is recommended to use SortedList<TKey, TValue> if we have to store and retrieve key/value pairs. The SortedDictionary<TKey, TValue> class is faster than the SortedList<TKey, TValue> class if we perform insertion and removal for unsorted data.
Features of the SortedList Function in C#
There are several features of the SortedList Function in C#. Some of them are as follows:
- In C#, this function is very useful to maintain the keys automatically in ascending order, which can be accessed by key or by index.
- It is used to give keys-values collections that can be iterated in sorted order.
- In C#, every key in the SortedList should be unique and cannot be null. However, the SortedList values can be duplicates or null.
- It is useful to implement several interfaces, including IDictionary<TKey, TValue>, ICollection<KeyValuePair<TKey, TValue>>, IEnumerable<KeyValuePair<TKey, TValue>>, and read-only methods.
- It takes an O(log n) complexity using the binary search on the keys, and enables direct access to values by index.
Conclusion
In summary, the C# SortedList<TKey, TValue> represents a swift, array-backed container that stores distinct keys and their corresponding values in a sorted manner based on the keys. This data structure enables rapid key-based and index-based searches for datasets of a moderate scale. It is most appropriate for scenarios that prioritize key retrieval, sequential access in order, and efficient memory usage over frequent insertions or removals. Ideal use cases include ordered lookup tables, ranking systems, and datasets where maintaining a consistent key order is crucial.
C# SortedList FAQs
1) What if a null or duplicate key is inserted?
In C#, attempting to insert a null or duplicate key will result in an exception being thrown.
2) How is SortedList<TKey, TValue> different from Dictionary<TKey, TValue> and SortedDictionary<TKey, TValue> in C#?
In C#, the SortedList<TKey, TValue> takes less memory and offers quicker retrieval when sorted already, but may be slower on insertion and deletion than SortedDictionary<TKey, TValue> since elements must be shifted. Dictionary<TKey, TValue> does not maintain any order of its elements.
The maximum time complexity of operations in SortedList<TKey, TValue> in C# is the worst-case scenario.
In C#, searching by key operates at O(log n) complexity. On the other hand, insertions and deletions have a worst-case time complexity of O(n) since rearranging elements is necessary to maintain order.
4) Is it possible for a SortedList in C# to include null values?
Yes, if TValue represents a reference type, values can indeed be null. However, it's important to note that keys must always have a non-null value.
5) Can we iterate over the elements in order?
Yes, cycling through a SortedList<TKey, TValue> results in elements being presented in increasing order based on keys.