C# SortedList

The SortedList is a collection class in C# to store key/ value pairs. The key must be unique and cannot be null. It is sorted by keys.

C# has both generic and non-generic SortedList. Since the generic SortedList<TKey, TValue> is faster, it should be preferred. The generic SortedList class is defined in the System.Collections.Generics namespace:

Create a SortedList

To create a SortedList with an int key and string value pair, use <int, string>. Set the type in angular braces in the case of the generic SortedList.

Let us create a SortedList. The result will get sorted by keys automatically:

Output

Access SortedList elements

To access a value from a SortedList, use the key value. Set the key of the value you want to access as an indexer. Let us see an example:

Output

Delete a SortedList element

To delete a specific key/ value pair, set the key as a parameter of the Remove() method. Let us see an example and delete a key/ value par:

Output

Display only the keys

To display only the keys from the key/ value pair of a SortedList, use the keys property. Let us see an example:

Output

Display only the values

To display only the values from the key/ value pair of a SortedList, use the Values property. Let us see an example:

Output

Check the SortedList for a specific key

The ContainsKey() method allows you to check a SortedList for a key. Let us see an example:

Output

Check the SortedList for a specific value

The ContainsValue() method allows you to check a SortedList for a value. Let us see an example:

Output


Read More

C# - Installation and Setup
C# vs Java - Difference
Studyopedia Editorial Staff
contact@studyopedia.com

We work to create programming tutorials for all.

No Comments

Post A Comment

Discover more from Studyopedia

Subscribe now to keep reading and get access to the full archive.

Continue reading