how to print dictionary in c# with for loop code example

Example: how to print dictionary in c# with for loop

using System;
using System.Linq;
using System.Collections.Generic;
 
public class Example
{
    public static void PrintDict(Dictionary dict)
    {
        for (int i = 0; i < dict.Count; i++)
        {
            KeyValuePair entry = dict.ElementAt(i);
            Console.WriteLine(entry.Key + " : " + entry.Value);
        }
    }
 
    public static void Main()
    {
        Dictionary dict = new Dictionary
        {
            { "key1", "value1" },
            { "key2", "value2" }
        };
 
        PrintDict(dict);
    }
}
 
/*
    Output:
 
    key1 : value1
    key2 : value2
*/

Tags:

Misc Example