C# C# Console Application

How to Retrieve a Key-Value Pair from a Dictionary in C#3 min read

Dictionaries in C# are one of the most versatile data structures, allowing developers to store data in key-value pairs. If you’re working with a dictionary and need to retrieve a specific key-value pair by index, this tutorial will guide you step-by-step.

In this article, you’ll learn:

  • How to initialize a dictionary in C#.
  • How to iterate through a dictionary to display its keys and values.
  • How to retrieve a specific key-value pair using methods like ElementAt() and ElementAtOrDefault().




Let’s dive right into an example.

Example Code

Here’s a complete example of a C# program that demonstrates how to retrieve a key-value pair from a dictionary:

 Output

When you run the program, you will see the following output:

 

 Explanation

1. Iterating Through the Dictionary

The program first iterates through the dictionary using a foreach loop to print all key-value pairs. Each pair consists of a key (int) and a value (string).

2. Retrieving a Key-Value Pair by Index

The ElementAt() method from the System.Linq namespace allows us to access a key-value pair at a specific index in the dictionary. However, keep in mind that dictionaries do not guarantee order, so the index order may vary.

  • ElementAt(1) retrieves the key-value pair at index 1 (the second item).
  • ElementAtOrDefault(3) retrieves the key-value pair at index 3 (the fourth item). If the index is out of range, it will return the default value (an empty key-value pair).

3. Output Explanation

The retrieved key-value pairs are displayed on the console:

  • At index 1, the key-value pair is 20 ........ Great Skua.
  • At index 3, the key-value pair is 40 ........ Little Auk

Important Notes

  1. Dictionaries Are Unordered
    Although the example retrieves key-value pairs by index, dictionaries in C# do not guarantee the order of elements. If maintaining order is critical, consider using a SortedDictionary or a List<KeyValuePair<TKey, TValue>>.
  2. When to Use ElementAtOrDefault
    Use ElementAtOrDefault to safely access an index that may or may not exist. If the index is out of range, it will prevent exceptions and return a default key-value pair.

Key Takeaways

  • The ElementAt() method is useful for accessing a dictionary element at a specific index.
  • Use ElementAtOrDefault() to avoid exceptions when the index might not exist.
  • Remember that dictionaries are unordered, so the index may vary depending on the implementation.

Conclusion

By following this guide, you can confidently work with dictionaries in C# and retrieve specific key-value pairs using their index. If you have further questions or need additional examples, feel free to leave a comment below!

Leave a Comment