Javatpoint Logo
Javatpoint Logo

SortedDictionary.Keys Property in C#

A dictionary is a collection type in C# that includes key-value pairs, allowing for quick access to things by unique keys. The Dictionary<TKey, TValue> class in C# is part of the .NET Framework and is frequently used to build dictionaries.

The SortedDictionary<TKey, TValue> is a collection containing sorted key-value pairs. The Keys property of SortedDictionary<TKey, TValue> gives access to a structured set representing the dictionary's keys.

Syntax:

It has the following Syntax:

Return Value:

It reruns the collection of keys.

Key characteristics include:

There are several characteristics of the SortedDictionary.Keys Property in C#. Some characteristics of this property are as follows:

  • Ordered Collection: The Keys property returns the keys in the dictionary in the order they have been created, or by using the custom comparer provided when the SortedDictionary was formed.
  • KeyCollection Is Immutable: The KeyCollection created by Keys is immutable, which means that its elements cannot be directly modified.

Complexity and performance:

  • Access Complexity: The Keys property provides a direct reference to the organized collection of keys. Hence, it represents an O(1) oepration.
  • Iterating difficulty: It iterating through a KeyCollection has an O(n) difficulty because it requires traversal of all keys.

Considerations as well as Use Cases:

  • Key Retrieval: When you only require the keys from the SortedDictionary, the Keys property makes it simple to find them.
  • It is handy for iterating over keys while doing operations on the dictionary's related values.

Best Practices and Considerations:

  • Immutable Collection: Changes made to the original SortedDictionary have no impact on the KeyCollection because it is an immutable collection.
  • Changes Should Be Avoided: Because the KeyCollection is meant to be read-only, altering the keys within it may result in exceptions.

Limitations and Exemptions:

  • Modifying the KeyCollection (adding or removing keys) results in NotSupportedException.

Example 1:

Let us take an example to implement the dictionary function in C#.

Output:

The total number of key/value pairs in myD are : 6
Key = Belgium
Key = China
Key = France
Key = Germany
Key = Oman
Key = Spain

Example 2:

Let us take another example to implement the dictionary function in C#.

Output:

The total number of key/value pairs in myD are : 6
Key = 0
Key = 1
Key = 2
Key = 3
Key = 4
Key = 5






Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA