KeyValuePair<(Of <(TKey, TValue>)>) 結構
定義可設置或檢索的鍵/值對。
命名空間:
System.Collections.Generic
程序集: mscorlib(在 mscorlib.dll 中)
語法 C#
public struct KeyValuePair<TKey, TValue>
備註
Dictionary<(Of <(TKey, TValue>)>)..::.Enumerator..::.Current 屬性返回此類型的實例。
C# 語言中的 foreach 語句(在 C++ 中爲 for each,在 Visual Basic 中爲 For Each)需要集合中的元素類型。由於基於 IDictionary<(Of <(TKey, TValue>)>) 的集合中的每個元素都是一個鍵/值對,因此元素類型既不是鍵的類型,也不是值的類型。而是 KeyValuePair<(Of <(TKey, TValue>)>) 類型。例如
foreach (KeyValuePair<int, string> kvp in myDictionary) {...}
foreach 語句是對枚舉數的包裝,該枚舉數只允許從集合中讀取,不允許寫入集合中。
示例 1
下面的代碼示例演示如何使用 KeyValuePair<(Of <(TKey, TValue>)>) 結構枚舉字典中的鍵和值。
此代碼摘自一個爲 Dictionary<(Of <(TKey, TValue>)>) 類提供的更大的示例(第二個示例)。
// When you use foreach to enumerate dictionary elements,
// the elements are retrieved as KeyValuePair objects.
outputBlock.Text += "\n";
foreach (KeyValuePair<string, string> kvp in openWith)
{
outputBlock.Text += String.Format("Key = {0}, Value = {1}",
kvp.Key, kvp.Value) + "\n";
}
實例二
//引入命名空間
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
代碼:
Dictionary<int, string> dic = new Dictionary<int, string>();
dic.Add(1, "一號");
dic.Add(2, "二號");
dic.Add(3, "三號");
dic.Add(4, "四號");
dic.Add(5, "五號");
dic.Add(6, "六號");
var result = from pairs in dic orderby pairs.Key select pairs;
foreach (KeyValuePair<int, string> pair in result)
{
Console.WriteLine("Key:{0}, Value:{1}", pair.Key, pair.Value);
}
注意:運行環境.Net Framework 3.5
類型參數
TKey
鍵的類型。
TValue
值的類型。