- Trending Categories
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() 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
Advertisements