
- C# Basic Tutorial
- C# - Home
- C# - Overview
- C# - Environment
- C# - Program Structure
- C# - Basic Syntax
- C# - Data Types
- C# - Type Conversion
- C# - Variables
- C# - Constants
- C# - Operators
- C# - Decision Making
- C# - Loops
- C# - Encapsulation
- C# - Methods
- C# - Nullables
- C# - Arrays
- C# - Strings
- C# - Structure
- C# - Enums
- C# - Classes
- C# - Inheritance
- C# - Polymorphism
- C# - Operator Overloading
- C# - Interfaces
- C# - Namespaces
- C# - Preprocessor Directives
- C# - Regular Expressions
- C# - Exception Handling
- C# - File I/O
- C# Advanced Tutorial
- C# - Attributes
- C# - Reflection
- C# - Properties
- C# - Indexers
- C# - Delegates
- C# - Events
- C# - Collections
- C# - Generics
- C# - Anonymous Methods
- C# - Unsafe Codes
- C# - Multithreading
- C# Useful Resources
- C# - Questions and Answers
- C# - Quick Guide
- C# - Useful Resources
- C# - Discussion
How to iterate over a C# dictionary?
Firstly, add elements −
IDictionary<int, int> d = new Dictionary<int, int>(); d.Add(1,97); d.Add(2,89); d.Add(3,77); d.Add(4,88);
Now, get the keys −
List<int> myList = new List<int>(d.Keys);
To iterate −
foreach (int k in myList) { Console.WriteLine("{0}, {1}", k, d[k]); }
The following is an example −
Example
using System; using System.Collections.Generic; public class Demo { public static void Main() { IDictionary < int, int > d = new Dictionary < int, int > (); d.Add(1, 97); d.Add(2, 89); d.Add(3, 77); d.Add(4, 88); List < int > myList = new List < int > (d.Keys); foreach(int k in myList) { Console.WriteLine("{0}, {1}", k, d[k]); } } }
Output
1, 97 2, 89 3, 77 4, 88
- Related Articles
- C++ Program to Iterate Over a Dictionary
- Iterate over a dictionary in Python
- How to Iterate over Tuples in Dictionary using Python
- What is the best way to iterate over a Dictionary in C#?
- How to iterate over a Java list?
- How to iterate over a C# list?
- How to iterate over a C# tuple?
- How to iterate through a dictionary in Python?
- How to recursively iterate a nested Python dictionary?
- How to iterate over a Hashmap in Kotlin?
- How to iterate over a list in Java?
- How to iterate over all MongoDB databases?
- Java Program to Iterate over a HashMap
- Java Program to Iterate over a Set
- Golang program to iterate over a Slice

Advertisements