Accessing Values in C# Key-Value Pair List
In C#, a key-value pair list, often implemented as a Dictionary<TKey, TValue>, allows you to store and retrieve data associatively. This means you can access values not by their index, but by a unique key. This article guides you through the process of getting a value by its key in C#.
Understanding Key-Value Pair Lists
Before diving into accessing values, let's understand key-value pair lists. In C#, a Dictionary<TKey, TValue> is a generic collection that is organized based on a key. The key is unique for each element, and the value can be any object. Here's a simple example:
Dictionary<string, int> ages = new Dictionary<string, int>();
ages.Add("John", 30);
ages.Add("Jane", 25);
Getting a Value by Key
The TryGetValue method is the recommended way to get a value by its key. It retrieves the value if the key exists, and returns a default value if the key is not found. Here's how you can use it:

int johnsAge;
if (ages.TryGetValue("John", out johnsAge))
{
Console.WriteLine($"John is {johnsAge} years old.");
}
else
{
Console.WriteLine("John's age not found.");
}
Using the Indexer
You can also use the indexer to get a value by its key. However, this will throw a KeyNotFoundException if the key is not found. Here's how you can use it:
int janeAge = ages["Jane"];
Console.WriteLine($"Jane is {janeAge} years old.");
Note: Using the indexer without checking if the key exists can lead to runtime exceptions. Always use TryGetValue when possible.
Performance Considerations
Accessing values by key in a Dictionary<TKey, TValue> is generally fast, with an average time complexity of O(1). However, this can degrade to O(n) in the worst case if the hash function produces many collisions. To minimize this, use a good hash function and keep your key data distributed.

Conclusion
In this article, we've explored how to get a value by its key in a C# key-value pair list. We've covered the recommended TryGetValue method, as well as the indexer approach. Always remember to handle potential key not found exceptions to keep your code robust and maintainable.






















