What method is used to traverse a dictionary in C#?

In C#, there are several ways to iterate through a dictionary.

  1. Loop through key-value pairs in a dictionary using a foreach loop.
Dictionary<string, int> dict = new Dictionary<string, int>();

foreach (KeyValuePair<string, int> kvp in dict)
{
    string key = kvp.Key;
    int value = kvp.Value;
    Console.WriteLine("Key: {0}, Value: {1}", key, value);
}
  1. Traverse the keys in a dictionary using a foreach loop.
Dictionary<string, int> dict = new Dictionary<string, int>();

foreach (string key in dict.Keys)
{
    int value = dict[key];
    Console.WriteLine("Key: {0}, Value: {1}", key, value);
}
  1. Iterate through the values in a dictionary using a foreach loop.
Dictionary<string, int> dict = new Dictionary<string, int>();

foreach (int value in dict.Values)
{
    Console.WriteLine("Value: {0}", value);
}
  1. Traverse key-value pairs in a dictionary using LINQ query expressions.
Dictionary<string, int> dict = new Dictionary<string, int>();

var query = from kvp in dict
            select kvp;

foreach (var kvp in query)
{
    string key = kvp.Key;
    int value = kvp.Value;
    Console.WriteLine("Key: {0}, Value: {1}", key, value);
}
bannerAds