溫馨提示×

C#字典遍歷有哪些技巧

c#
小樊
113
2024-07-30 14:45:10
欄目: 編程語言

在C#中,可以使用以下技巧來遍歷字典:

  1. 使用foreach循環遍歷字典中的鍵值對:
Dictionary<string, int> dictionary = new Dictionary<string, int>();

foreach (var item in dictionary)
{
    Console.WriteLine($"Key: {item.Key}, Value: {item.Value}");
}
  1. 使用字典的Keys屬性遍歷字典中的所有鍵:
Dictionary<string, int> dictionary = new Dictionary<string, int>();

foreach (string key in dictionary.Keys)
{
    Console.WriteLine($"Key: {key}, Value: {dictionary[key]}");
}
  1. 使用字典的Values屬性遍歷字典中的所有值:
Dictionary<string, int> dictionary = new Dictionary<string, int>();

foreach (int value in dictionary.Values)
{
    Console.WriteLine($"Value: {value}");
}
  1. 使用LINQ查詢語句來過濾或排序字典中的鍵值對:
Dictionary<string, int> dictionary = new Dictionary<string, int>();

var sortedDictionary = dictionary.OrderBy(x => x.Value);

foreach (var item in sortedDictionary)
{
    Console.WriteLine($"Key: {item.Key}, Value: {item.Value}");
}

這些技巧可以幫助您更有效地遍歷和處理字典中的數據。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女