To iterate over the keys in a dictionary in C#, you can use a `foreach` loop to loop through the `Keys` property of the `Dictionary
We can iterate over the keys in a dictionary in C# using a `foreach` loop. This example demonstrates how to loop through the keys of a dictionary and print each key.
For example,
using System.Collections.Generic;
.myDictionary
with integer keys and string values.using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// Declare and initialize a dictionary
Dictionary<int, string> myDictionary = new Dictionary<int, string>
{
{1, "One"},
{2, "Two"},
{3, "Three"}
};
// Iterate over the keys in the dictionary
Console.WriteLine("Keys in the dictionary:");
foreach (int key in myDictionary.Keys)
{
Console.WriteLine("Key: {0}", key);
}
}
}
Keys in the dictionary: Key: 1 Key: 2 Key: 3
We can iterate over the keys in a dictionary in C# using a `foreach` loop and access the corresponding values. This example demonstrates how to loop through the keys of a dictionary and print each key along with its associated value.
For example,
using System.Collections.Generic;
.myDictionary
with integer keys and string values.using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// Declare and initialize a dictionary
Dictionary<int, string> myDictionary = new Dictionary<int, string>
{
{1, "One"},
{2, "Two"},
{3, "Three"}
};
// Iterate over the keys in the dictionary and access corresponding values
Console.WriteLine("Keys and values in the dictionary:");
foreach (int key in myDictionary.Keys)
{
string value = myDictionary[key];
Console.WriteLine("Key: {0}, Value: {1}", key, value);
}
}
}
Keys and values in the dictionary: Key: 1, Value: One Key: 2, Value: Two Key: 3, Value: Three
In this tutorial, we learned How to Iterate over Keys in a Dictionary in C# language with well detailed examples.