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

 Live Demo

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

Updated on: 22-Jun-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements