How to Get Values by Key in Dictionary in C#
In C#, there are several methods for getting the values by key in the dictionary:
1: Using Index Operator
You can use the index operator in C# to retrieve the value associated with a key in a dictionary and it can be done using the following steps:
Step 1: The first step is to construct a Dictionary class instance. Both an empty dictionary and certain key-value pairs can be used as their starting values.
For instance, to create a dictionary of string keys and integer values, you can use the following code:
Step 2: Then add some pairs to the dictionary as follows:
MyDictionary.Add("brown", 2);
MyDictionary.Add("white", 3);
Note: The above two steps will remain the same for all methods mentioned in this article.
Step 3: The key may then be used as the index in the square bracket notation to retrieve the value associated with a certain key.
Use the following code, for instance, to retrieve the value linked to the key “brown“:
The variable value is given the value 2 by this code. This code will produce a KeyNotFoundException if the key isn’t found in the dictionary.
To avoid this, use the ContainsKey method to determine if the key is present in the dictionary.
For example:
{
int value = MyDictionary["brown"];
Console.WriteLine("The value is " + value);
}
else
{
Console.WriteLine("The key does not exist in the dictionary.");
}
The above code checks whether key brown exists in the dictionary. If it does, it retrieves the value and prints it. If not, an error message stating that the key is missing from the dictionary is printed.
Here is the entire C# code for the above-mentioned method:
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
// Create an empty dictionary with string keys and integer values
Dictionary MyDictionary = new Dictionary();
// Add some key-value pairs to the dictionary
MyDictionary.Add("black", 1);
MyDictionary.Add("brown", 2);
MyDictionary.Add("white", 3);
// Check whether the key exists in the dictionary before getting the value
if (MyDictionary.ContainsKey("brown"))
{
int value = MyDictionary["brown"];
Console.WriteLine("The value is " + value);
}
else
{
Console.WriteLine("The key does not exist in the dictionary.");
}
// Wait for user input to close the console window
Console.ReadKey();
}
}
2: Using TryGetValue()
You may get the value connected to a specific key by using the TryGetValue() method in addition to the square bracket syntax. If the key is in the dictionary, this function returns true and assigns the value to an output parameter. For example:
using System.Collections.Generic;
class Program
{
static void Main()
{
Dictionary MyDictionary = new Dictionary();
MyDictionary.Add("black", 1);
MyDictionary.Add("brown", 2);
MyDictionary.Add("white", 3);
int val;
if (MyDictionary.TryGetValue("brown", out val))
{
Console.WriteLine("The value is " + val);
}
else
{
Console.WriteLine("The key does not exist in the dictionary.");
}
}
}
The above code checks whether the key brown exists in the dictionary, and assigns the value to the variable value if it does. It produces a message stating that the key is missing from the dictionary if it cannot be located.
3: Using LINQ (Language-Integrated Query)
You can also use LINQ queries to get a value by key in a Dictionary. LINQ queries enable us to run complicated queries on data sources such as Dictionaries.
Here’s an illustration:
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
Dictionary MyDictionary = new Dictionary();
MyDictionary.Add("black", 1);
MyDictionary.Add("brown", 2);
MyDictionary.Add("white", 3);
string keyToFind = "brown";
var result = MyDictionary.FirstOrDefault(x => x.Key == keyToFind);
if (result.Equals(default(KeyValuePair)))
{
Console.WriteLine($"The key '{keyToFind}' does not exist in the dictionary.");
}
else
{
Console.WriteLine($"The value associated with the key '{keyToFind}' is {result.Value}.");
}
}
}
The above code declares a class called Program with a Main method that creates a dictionary with string keys and integer values. The dictionary is then populated with some values. The code then searches for a specific key in the dictionary using the FirstOrDefault() LINQ method and outputs a message depending on whether the key was found or not.
Conclusion
Retrieving the value by key in a dictionary is a vital operation in C# programming as it enables you to access data by utilizing specific keys that map to values. This article explored three methods for getting values by key in a dictionary: using the index operator, TryGetValue() method, and LINQ queries. By using these methods, you can manipulate dictionary data easily and efficiently in your C# code.