To check if a value exists in a dictionary in C#, you can use the `ContainsValue` method of the `Dictionary
We can check if a value exists in a dictionary in C# using the `ContainsValue` method. This example demonstrates how to check for the presence of a value and print a message based on the result.
For example,
using System.Collections.Generic;
.myDictionary
with integer keys and string values.using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// Declare and initialize a dictionary
Dictionary<int, string> myDictionary = new Dictionary<int, string>
{
{1, "One"},
{2, "Two"},
{3, "Three"}
};
// Value to check
string valueToCheck = "Two";
// Check if the value exists using the ContainsValue method
if (myDictionary.ContainsValue(valueToCheck))
{
Console.WriteLine("Value '{0}' exists in the dictionary.", valueToCheck);
}
else
{
Console.WriteLine("Value '{0}' does not exist in the dictionary.", valueToCheck);
}
}
}
Value 'Two' exists in the dictionary.
We can check if a value does not exist in a dictionary in C# using the `ContainsValue` method. This example demonstrates how to check for the absence of a value and print a message based on the result.
For example,
using System.Collections.Generic;
.myDictionary
with integer keys and string values.using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// Declare and initialize a dictionary
Dictionary<int, string> myDictionary = new Dictionary<int, string>
{
{1, "One"},
{2, "Two"},
{3, "Three"}
};
// Value to check
string valueToCheck = "Four";
// Check if the value does not exist using the ContainsValue method
if (!myDictionary.ContainsValue(valueToCheck))
{
Console.WriteLine("Value '{0}' does not exist in the dictionary.", valueToCheck);
}
else
{
Console.WriteLine("Value '{0}' exists in the dictionary.", valueToCheck);
}
}
}
Value 'Four' does not exist in the dictionary.
In this tutorial, we learned How to Check if a Value Exists in a Dictionary in C# language with well detailed examples.