C# program to get the List of keys from a Dictionary


Set the dictionary elements −

Dictionary<int, string> d = new Dictionary<int, string>();

// dictionary elements
d.Add(1, "One");
d.Add(2, "Two");
d.Add(3, "Three");
d.Add(4, "Four");
d.Add(5, "Five");
d.Add(6, "Six");
d.Add(7, "Seven");
d.Add(8, "Eight");

To get the keys, use a list collection −

List<int> keys = new List<int>(d.Keys);

Loop through the keys and display them.

Here is the complete code −

Example

 Live Demo

using System;
using System.Collections.Generic;
public class Demo {
   public static void Main() {
      Dictionary<int, string> d = new Dictionary<int, string>();
      // dictionary elements
      d.Add(1, "One");
      d.Add(2, "Two");
      d.Add(3, "Three");
      d.Add(4, "Four");
      d.Add(5, "Five");
      d.Add(6, "Six");
      d.Add(7, "Seven");
      d.Add(8, "Eight");
      // getting keys
      List<int> keys = new List<int>(d.Keys);
      Console.WriteLine("Displaying keys...");
      foreach (int res in keys) {
         Console.WriteLine(res);
      }
   }
}

Output

Displaying keys...
1
2
3
4
5
6
7
8

Updated on: 22-Jun-2020

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements