To check if a key exists in a dictionary in C#, you can use the `ContainsKey` method of the `Dictionary
We can check if a key exists in a dictionary in C# using the `ContainsKey` method. This example demonstrates how to check for the presence of a key 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"}
};
// Key to check
int keyToCheck = 2;
// Check if the key exists using the ContainsKey method
if (myDictionary.ContainsKey(keyToCheck))
{
Console.WriteLine("Key {0} exists in the dictionary.", keyToCheck);
}
else
{
Console.WriteLine("Key {0} does not exist in the dictionary.", keyToCheck);
}
}
}
Key 2 exists in the dictionary.
We can check if a key does not exist in a dictionary in C# using the `ContainsKey` method. This example demonstrates how to check for the absence of a key 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"}
};
// Key to check
int keyToCheck = 4;
// Check if the key does not exist using the ContainsKey method
if (!myDictionary.ContainsKey(keyToCheck))
{
Console.WriteLine("Key {0} does not exist in the dictionary.", keyToCheck);
}
else
{
Console.WriteLine("Key {0} exists in the dictionary.", keyToCheck);
}
}
}
Key 4 does not exist in the dictionary.
In this tutorial, we learned How to Check if a Key Exists in a Dictionary in C# language with well detailed examples.