
- C# Basic Tutorial
- C# - Home
- C# - Overview
- C# - Environment
- C# - Program Structure
- C# - Basic Syntax
- C# - Data Types
- C# - Type Conversion
- C# - Variables
- C# - Constants
- C# - Operators
- C# - Decision Making
- C# - Loops
- C# - Encapsulation
- C# - Methods
- C# - Nullables
- C# - Arrays
- C# - Strings
- C# - Structure
- C# - Enums
- C# - Classes
- C# - Inheritance
- C# - Polymorphism
- C# - Operator Overloading
- C# - Interfaces
- C# - Namespaces
- C# - Preprocessor Directives
- C# - Regular Expressions
- C# - Exception Handling
- C# - File I/O
- C# Advanced Tutorial
- C# - Attributes
- C# - Reflection
- C# - Properties
- C# - Indexers
- C# - Delegates
- C# - Events
- C# - Collections
- C# - Generics
- C# - Anonymous Methods
- C# - Unsafe Codes
- C# - Multithreading
- C# Useful Resources
- C# - Questions and Answers
- C# - Quick Guide
- C# - Useful Resources
- C# - Discussion
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
- Related Articles
- ContainsKey() method in C#
- isless() in C/C++
- islessgreater() in C/C++
- isgreater() in C/C++
- modf() in C/C++
- isblank() in C/C++
- islessequal() in C/C++
- strxfrm() in C/C++
- Comments in C/C++
- isgreaterequal() in C/C++
- ungetc() in C/C++
- (limits.h) in C/C++
- Pointers in C/C++
- fseek() in C/C++
- strcpy() in C/C++

Advertisements