溫馨提示×

c# KeyValuePair的用法

c#
小億
338
2024-01-11 06:22:32
欄目: 編程語言

在C#中,KeyValuePair<TKey, TValue> 是一種表示鍵值對的結構體。它定義了兩個屬性,Key和Value,分別表示鍵和值。

KeyValuePair<TKey, TValue>可以用于以下幾種情況:

  1. 在循環中遍歷字典:可以使用KeyValuePair<TKey, TValue>在循環中遍歷一個字典(Dictionary<TKey, TValue>)的鍵值對。例如:
Dictionary<string, int> dict = new Dictionary<string, int>();
dict.Add("apple", 1);
dict.Add("orange", 2);

foreach (KeyValuePair<string, int> kvp in dict)
{
    Console.WriteLine("Key: " + kvp.Key + ", Value: " + kvp.Value);
}

輸出結果:

Key: apple, Value: 1
Key: orange, Value: 2
  1. 將鍵值對作為方法的參數或返回值:可以使用KeyValuePair<TKey, TValue>作為方法的參數或返回值,以傳遞或返回鍵值對。例如:
public KeyValuePair<string, int> GetMaxValue(Dictionary<string, int> dict)
{
    KeyValuePair<string, int> maxKvp = new KeyValuePair<string, int>(null, int.MinValue);

    foreach (KeyValuePair<string, int> kvp in dict)
    {
        if (kvp.Value > maxKvp.Value)
        {
            maxKvp = kvp;
        }
    }

    return maxKvp;
}
  1. 在LINQ查詢中使用:可以使用KeyValuePair<TKey, TValue>在LINQ查詢中對結果進行分組或排序。例如:
var dict = new Dictionary<string, int>()
{
    { "apple", 1 },
    { "orange", 2 },
    { "banana", 3 },
    { "grape", 4 }
};

var sortedDict = dict.OrderBy(kvp => kvp.Value);

foreach (KeyValuePair<string, int> kvp in sortedDict)
{
    Console.WriteLine("Key: " + kvp.Key + ", Value: " + kvp.Value);
}

輸出結果:

Key: apple, Value: 1
Key: orange, Value: 2
Key: banana, Value: 3
Key: grape, Value: 4

總之,KeyValuePair<TKey, TValue>可以用于表示鍵值對,并且可以在循環、方法參數、返回值以及LINQ查詢中使用。

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