Multiple ways to check Key in Dictionary
How to check that key exists in a dictionary or not
1. Contains Key
It is most common way to check if a key exists or not in dictionary , it returns bool value.
2. Using Index way
It checks the key and if it is not found it will throw , key not found exception , use try catch to avoid it .
3. Using TryGetValue
It checks if the key exists or not and it will not throw the exception if value was not found.
4. Using custom extension method
You can create an extension method for your dictionary and check the key by iterating over dictionary via contains method
Here it is check example.
If you want to help the author in growing
- Subscribe my Weekly .NET Newsletter of C#/.NET
- Follow me on LinkedIn/Twitter OR Clap at least 50 times.
- Get exclusive .NET Questions & Answers by becoming a Patron.
- Download my eBook at Gumroad that contains 30 .NET Tips.