C# – Check if a value exists in dictionary

Normally you’d check if a dictionary contains a key or get a value by key. But you can also check if the dictionary contains a specific value by using Dictionary.ContainsValue(). Here’s an example:

using System.Collections.Generic;

var dictionary = new Dictionary<string, int>()
{
    ["Bob"] = 1
};

bool contains1 = dictionary.ContainsValue(1);
Console.WriteLine($"Contains 1? {contains1}"); //True

bool contains2 = dictionary.ContainsValue(2);
Console.WriteLine($"Contains 2? {contains2}"); //False
Code language: C# (cs)

Dictionary.ContainsValue() returns true if the value was found and otherwise returns false. In this example, I initialized the dictionary with a single item with value=1, so this outputs the following:

Contains 1? True
Contains 2? FalseCode language: plaintext (plaintext)

When the dictionary has reference type values

There are two scenarios for checking the dictionary for a value when you’re using reference types (i.e. a class):

  • Use Any() (Linq) when you want to look for an object by property.
  • Use Dictionary.ContainsValue() when you want to look for an object by reference.

I’ll show examples below.

Check for object with a property

Use Dictionary.Values.Any() and supply a lambda for looking for an object having a property with a specific value. Here’s an example:

using System.Collections.Generic;
using System.Linq;

var dictionary = new Dictionary<int, Person>
{
    [1] = new Person() { Id = 1, FirstName = "Bob", LastName = "Belcher" }
};

bool containsBob = dictionary.Values.Any(p => p.FirstName == "Bob");

Console.WriteLine($"Contains Person with FirstName=Bob? {containsBob}"); //True
Code language: C# (cs)

This looks for a person with first name “Bob” and outputs the following:

Contains Person with FirstName=Bob? TrueCode language: plaintext (plaintext)

Note: You could also loop through the dictionary and check each value. Using Any() is just a nice shortcut for doing that.

Check for object reference

Dictionary.ContainsValue() uses the reference type’s default equality comparer. This means it compares objects by reference (unless you’ve created an equality comparer for the class). Here’s an example of checking if a specific object reference exists in the dictionary:

using System.Collections.Generic;

Person bob = new Person() { Id = 1, FirstName = "Bob", LastName = "Belcher" };

var dictionary = new Dictionary<int, Person>
{
    [1] = bob
};

bool containsBob = dictionary.ContainsValue(bob);

Console.WriteLine($"Contains 'bob' object reference? {containsBob}"); //True
Code language: C# (cs)

The ‘bob’ object reference was added to the dictionary. Then Dictionary.ContainsValue() was used to check for the ‘bob’ object reference. Since that reference exists in the dictionary, it returns true. This example outputs the following:

Contains 'bob' object reference? TrueCode language: plaintext (plaintext)