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

CsharpProgrammingServer Side Programming

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
raja
Published on 04-Sep-2018 12:35:22
Advertisements