Dictionaries store key/value pairs. When you want to get the value for a key, you can use the indexer syntax and specify the key, like this:
using System.Collections.Generic;
var dictionary = new Dictionary<string, int>()
{
["Bob"] = 1,
["Linda"] = 2
};
//Get value by key with indexer
var val = dictionary["Bob"];
Console.WriteLine($"Bob={val}");
Code language: C# (cs)
Note: In order to show how to get a value, I had to initialize the dictionary with key/value pairs.
This returns the value associated with the “Bob” key and outputs the following:
Bob=1
Code language: plaintext (plaintext)
This is the most direct way to get a value by key. However, if the key doesn’t exist, it throws a KeyNotFoundException. In the next sections, I’ll explain how to deal with the possibility of the key not existing. At the end, I’ll show how to get all values (in case you don’t want a specific key’s value).
Table of Contents
Get the value if the key exists
You can use Dictionary.TryGetValue() to safely attempt to get a value. If the key exists, it outputs the value via the out parameter and the method returns true. If the key doesn’t exist, it returns false.
using System.Collections.Generic;
var dictionary = new Dictionary<string, int>()
{
["Bob"] = 1,
["Linda"] = 2
};
if (dictionary.TryGetValue("Bob", out int val))
{
Console.WriteLine($"Bob={val}");
}
Code language: C# (cs)
Note: If the key isn’t found, the out parameter is left as the default value for that type (i.e. 0 for int).
In this example, the “Bob” key exists, so TryGetValue() returns true and sets the out parameter to 1. This outputs:
Bob=1
Code language: plaintext (plaintext)
Alternative: Use Dictionary.ContainsKey() + indexer
TryGetValue() is basically a shortcut for using Dictionary.ContainsKey() and then fetching the value with the indexer. You can of course do this yourself if it makes sense in your scenario. Sometimes this is simpler than using TryGetValue(). Here’s an example:
if (dictionary.ContainsKey("Bob"))
{
var val = dictionary["Bob"];
Console.WriteLine($"Bob={val}");
}
Code language: C# (cs)
This outputs:
Bob=1
Code language: plaintext (plaintext)
Get the value or default if the key doesn’t exist
Let’s say you want to get the value for a key or get a default value (such as 0) if the key doesn’t exist. The best way to do that is by using Dictionary.GetValueOrDefault(). Here’s an example:
using System.Collections.Generic;
var dictionary = new Dictionary<string, int>()
{
["Bob"] = 1,
["Linda"] = 2
};
//Returns value for existing key
var bobValue = dictionary.GetValueOrDefault("Bob");
Console.WriteLine($"'Bob' key exists and has value={bobValue}");
//Returns default value (0) for existing key
var teddyValue = dictionary.GetValueOrDefault("Teddy");
Console.WriteLine($"'Teddy' key doesn't exist, so default value={teddyValue}");
Code language: C# (cs)
This outputs:
'Bob' key exists and has value=1
'Teddy' key doesn't exist, so default value=0
Code language: plaintext (plaintext)
GetValueOrDefault() returns the default value for the type. In this example, dictionary’s value type is int, which has a default of 0. You can override the default value if you want. Here’s an example of using -1000 as the default (instead of 0):
using System.Collections.Generic;
var dictionary = new Dictionary<string, int>()
{
["Bob"] = 1,
["Linda"] = 2
};
var val = dictionary.GetValueOrDefault("Teddy", -1000);
Console.WriteLine($"Default value = {val}");
Code language: C# (cs)
This outputs:
Default value = -1000
Code language: plaintext (plaintext)
Get ALL values in the dictionary
In some cases, you may be interested in getting all of the dictionary’s values, instead of specifying a key and getting a single value. To get all values, use Dictionary.Values. You can use this to loop through the dictionary values, or whatever you want really.
Here’s an example:
using System.Collections.Generic;
using System.Linq;
var dictionary = new Dictionary<string, int>()
{
["Bob"] = 1,
["Linda"] = 1,
["Teddy"] = 2
};
var allValues = dictionary.Values;
var count = allValues.Count;
Console.WriteLine($"There are {count} values.");
var countOfOnes = allValues.Where(v => v == 1).Count();
Console.WriteLine($"How many 1's? {countOfOnes}");
Code language: C# (cs)
This outputs:
There are 3 values.
How many 1's? 2
Code language: plaintext (plaintext)