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()
andElementAtOrDefault()
.
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { // Initialize a dictionary with key-value pairs Dictionary<int, string> birds = new Dictionary<int, string>() { {10, "Parasitic Skua"}, {20, "Great Skua"}, {30, "Atlantic Puffin"}, {40, "Little Auk"}, {50, "Guillemot"} }; Console.WriteLine("Dictionary keys and values:"); foreach (KeyValuePair<int, string> pair in birds) { Console.WriteLine(pair.Key + " ........ " + pair.Value); } // Get the key-value pair at a specific index KeyValuePair<int, string> pairAtIndex1 = birds.ElementAt(1); // Index 1 KeyValuePair<int, string> pairAtIndex3 = birds.ElementAtOrDefault(3); // Index 3 // Display the key-value pairs retrieved Console.WriteLine("\nKeyValuePair at index 1:"); Console.WriteLine(pairAtIndex1.Key + " ........ " + pairAtIndex1.Value); Console.WriteLine("\nKeyValuePair at index 3:"); Console.WriteLine(pairAtIndex3.Key + " ........ " + pairAtIndex3.Value); Console.ReadLine(); } } |
Output
When you run the program, you will see the following output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | Dictionary keys and values: 10 ........ Parasitic Skua 20 ........ Great Skua 30 ........ Atlantic Puffin 40 ........ Little Auk 50 ........ Guillemot KeyValuePair at index 1: 20 ........ Great Skua KeyValuePair at index 3: 40 ........ Little Auk |
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
).
1 2 3 4 5 6 | foreach (KeyValuePair<int, string> pair in birds) { Console.WriteLine(pair.Key + " ........ " + pair.Value); } |
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).
1 2 3 4 | KeyValuePair<int, string> pairAtIndex1 = birds.ElementAt(1); KeyValuePair<int, string> pairAtIndex3 = birds.ElementAtOrDefault(3); |
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
- 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 aSortedDictionary
or aList<KeyValuePair<TKey, TValue>>
. - When to Use
ElementAtOrDefault
UseElementAtOrDefault
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!