c#字典遍歷使用的方法是什么

c#
小億
135
2024-01-09 23:34:33
欄目: 編程語言

在C#中,遍歷字典的方法有以下幾種:

  1. 使用foreach循環(huán)遍歷字典中的鍵值對(duì):
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. 使用foreach循環(huán)遍歷字典中的鍵:
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. 使用foreach循環(huán)遍歷字典中的值:
Dictionary<string, int> dict = new Dictionary<string, int>();

foreach (int value in dict.Values)
{
    Console.WriteLine("Value: {0}", value);
}
  1. 使用LINQ查詢表達(dá)式遍歷字典中的鍵值對(duì):
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);
}

0