C# Program to find a key in Dictionary

CsharpProgrammingServer Side Programming

Firstly, set a Dictionary collection with elements.

Dictionary<int, string> d = new Dictionary<int, string>() {
   {1,"Applianes"},
   {2, "Clothing"},
   {3,"Toys"},
   {4,"Footwear"},
   {5, "Accessories"}
};

Now, let’s say you need to check whether key 5 exists or not. For that, use ContainsKey() method. It returns True if key is found.

d.ContainsKey(5);

Let us see the complete code.

Example

 Live Demo

using System;
using System.Collections.Generic;
public class Program {
   public static void Main() {
      Dictionary<int, string> d = new Dictionary<int, string>() {
         {1,"Electronics"},
         {2, "Clothing"},
         {3,"Toys"},
         {4,"Footwear"},
         {5, "Accessories"}
      };
      foreach (KeyValuePair<int, string> ele in d) {
         Console.WriteLine("Key = {0}, Value = {1}", ele.Key, ele.Value);
      }
      Console.WriteLine("Key 5 exists? "+d.ContainsKey(5));
   }
}

Output

Key = 1, Value = Electronics
Key = 2, Value = Clothing
Key = 3, Value = Toys
Key = 4, Value = Footwear
Key = 5, Value = Accessories
Key 5 exists? True
raja
Published on 14-Sep-2018 13:34:13
Advertisements