Get all Dictionary keys having some value in C#
This post will discuss how to get all Dictionary keys having some value in C#.
1. Using Where() method
We can use the Where() method to filter a dictionary based on a predicate. The following code example demonstrates how we can use Where() with Select() method to fetch all the dictionary keys having a value of 2. Note that it requires LINQ and you need to add System.Linq namespace.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
using System; using System.Linq; using System.Collections.Generic; public class Example { public static void Main() { Dictionary<string, int> dict = new Dictionary<string, int>() { {"A", 1}, {"B", 2}, {"C", 3}, {"D", 4}, {"E", 2} }; var matchingKeys = dict.Where(kvp => kvp.Value == 2) .Select(kvp => kvp.Key); Console.WriteLine(String.Join(", ", matchingKeys)); // B, E } } |
2. Using Dictionary<TKey,TValue>.FirstOrDefault() Method
If all the values in the dictionary are unique or you need the first matching key, you can use the Dictionary<TKey,TValue>.FirstOrDefault() method. It returns the first element of a dictionary that satisfies a condition, or a default value if no element is found. This also requires LINQ.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
using System; using System.Linq; using System.Collections.Generic; public class Example { public static void Main() { Dictionary<string, int> dict = new Dictionary<string, int>() { {"A", 1}, {"B", 2}, {"C", 3}, {"D", 4}, {"E", 2} }; var key = dict.FirstOrDefault(x => x.Value == 2).Key; Console.WriteLine(key); // B } } |
3. Using foreach loop
Alternatively, you can write your custom logic for getting all Dictionary keys having specific value. Here’s what the code would look like using a foreach loop:
|
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 |
using System; using System.Collections.Generic; public static class Extensions { public static List<T> GetKeysByValue<T, W>(this IDictionary<T, W> dict, W value) { List<T> keys = new List<T>(); foreach (KeyValuePair<T, W> kvp in dict) { if (EqualityComparer<W>.Default.Equals(kvp.Value, value)) { keys.Add(kvp.Key); } } return keys; } } public class Example { public static void Main() { Dictionary<string, int> dict = new Dictionary<string, int>() { {"A", 1}, {"B", 2}, {"C", 3}, {"D", 4}, {"E", 2} }; var keys = dict.GetKeysByValue(2); Console.WriteLine(String.Join(", ", keys)); // B, E } } |
That’s all about getting all Dictionary keys having some value in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)