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.

Download  Run Code

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.

Download  Run Code

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:

Download  Run Code

That’s all about getting all Dictionary keys having some value in C#.