
- 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() method in C#
Set a Hashtable collection and add some elements to it.
Hashtable h = new Hashtable(); h.Add(1, "Sam"); h.Add(2, "Jack"); h.Add(3, "Andy"); h.Add(4, "Katie"); h.Add(5, "Beth"); h.Add(6, "Benjamin");
Use the ContainsKey() method to check whether a key exists in a Hashtable or not.
Let’s check for key 3. It returns True of the key is found.
h.ContainsKey(3));
Example
using System; using System.Collections; public class Demo { public static void Main() { Hashtable h = new Hashtable(); h.Add(1, "Sam"); h.Add(2, "Jack"); h.Add(3, "Andy"); h.Add(4, "Katie"); h.Add(5, "Beth"); h.Add(6, "Benjamin"); Console.WriteLine("Keys and Values list:"); foreach (var key in h.Keys ) { Console.WriteLine("Key = {0}, Value = {1}",key , h[key]); } Console.WriteLine("Does the specified key exist? "+h.ContainsKey(3)); } }
Output
Keys and Values list: Key = 6, Value = Benjamin Key = 5, Value = Beth Key = 4, Value = Katie Key = 3, Value = Andy Key = 2, Value = Jack Key = 1, Value = Sam Does the specified key exist? True
- Related Articles
- ContainsKey in C#
- Class method vs static method in Python
- Collections.replaceAll() method and List.replaceAll() method in Java
- The isEmpty() method of CopyOnWriteArrayList method in Java
- The hashCode() method of CopyOnWriteArrayList method in Java
- The clone() method of CopyOnWriteArrayList method in Java
- Default method vs static method in an interface in Java?
- Difference between Method Overloading and Method Overriding in Java
- Difference between Method Overriding and Method Hiding in C#
- Reference to a static method using method references in Java8
- Reference to an instance method using method references in Java8
- How does Promise.all() method differs from Promise.allSettled() method in JavaScript?
- How does Promise.any() method differs from Promise.race() method in JavaScript?
- Integer.lowestOneBit() method in Java
- Integer.numberOfLeadingZeros() method in Java

Advertisements