在C#中,你可以使用以下方法來(lái)獲取Dictionary中的值:
Dictionary<string, int> myDictionary = new Dictionary<string, int>();
myDictionary["apple"] = 5;
myDictionary["banana"] = 8;
int value = myDictionary["apple"]; // value = 5
TryGetValue
方法獲取值:Dictionary<string, int> myDictionary = new Dictionary<string, int>();
myDictionary["apple"] = 5;
myDictionary["banana"] = 8;
int value;
if (myDictionary.TryGetValue("apple", out value))
{
// value = 5
}
else
{
// 沒(méi)有找到鍵名為"apple"的項(xiàng)
}
Dictionary<string, int> myDictionary = new Dictionary<string, int>();
myDictionary["apple"] = 5;
myDictionary["banana"] = 8;
int value = (from pair in myDictionary where pair.Key == "apple" select pair.Value).FirstOrDefault(); // value = 5
請(qǐng)注意,如果鍵名不存在于字典中,使用上述方法可能會(huì)導(dǎo)致異常或返回默認(rèn)值。為了避免這種情況,你可以使用TryGetValue
方法或者LINQ查詢,它們都會(huì)在鍵名不存在時(shí)返回默認(rèn)值。