![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
ContainsKey in C#
ContainsKey is a Dictionary method in C# and check whether a key exists in the Dictionary or not.
Declare a Dictionary and add elements −
var dict = new Dictionary<string, int>() { {"TV", 1}, {"Home Theatre", 2}, {"Amazon Alexa", 3}, {"Google Home", 5}, {"Laptop", 5}, {"Bluetooth Speaker", 6} };
Now, let’s say you need to check for the existence of a particular element in the Dictionary. For that, use the ContainsKey() method −
if (dict.ContainsKey("Laptop") == true) { Console.WriteLine(dict["Laptop"]); }
The following is the code −
Example
using System; using System.Collections.Generic; public class Demo { public static void Main() { var dict = new Dictionary<string, int>() { {"TV", 1}, {"Home Theatre", 2}, {"Amazon Alexa", 3}, {"Google Home", 5}, {"Laptop", 5}, {"Bluetooth Speaker", 6} }; if (dict.ContainsKey("Laptop") == true) { Console.WriteLine(dict["Laptop"]); } if (dict.ContainsKey("Amazon Alexa") == true) { Console.WriteLine(dict["Amazon Alexa"]); } } }
Output
5 3
Advertisements