- 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
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
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
Advertisements