To iterate over the values in a dictionary in C#, you can use a `foreach` loop to loop through the `Values` property of the `Dictionary
We can iterate over the values in a dictionary in C# using a `foreach` loop. This example demonstrates how to loop through the values of a dictionary and print each 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 values in the dictionary
Console.WriteLine("Values in the dictionary:");
foreach (string value in myDictionary.Values)
{
Console.WriteLine("Value: {0}", value);
}
}
}
Values in the dictionary: Value: One Value: Two Value: Three
We can iterate over the values in a dictionary in C# using a `foreach` loop and access the corresponding keys. This example demonstrates how to loop through the values of a dictionary and print each value along with its associated 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 values in the dictionary and access corresponding keys
Console.WriteLine("Values and keys in the dictionary:");
foreach (string value in myDictionary.Values)
{
// Find the corresponding key for the value
foreach (var kvp in myDictionary)
{
if (kvp.Value == value)
{
Console.WriteLine("Key: {0}, Value: {1}", kvp.Key, value);
break;
}
}
}
}
}
Values and keys in the dictionary: Key: 1, Value: One Key: 2, Value: Two Key: 3, Value: Three
In this tutorial, we learned How to Iterate over Values in a Dictionary in C# language with well detailed examples.