2015-04-23 144 views
2

在我的桌面C#應用程序中,我從字典開始。我希望能夠檢查這本字典的關鍵。如果字典有這個鍵,我想將它傳遞給一個方法。如果字典沒有這個鍵,我想創建一個空白列表,然後傳遞它。我怎樣才能做到這一點?c#檢查字典中是否存在關鍵字,然後傳遞其值

我得到錯誤「給定的鍵不在字典中」。我可以添加一個默認,所以它永遠不可能是空嗎?

// myDic was declared as a Dictionary<string, List<string>  

// Here is how I call someFunction 
string text = SomeFunction(stringValue1, stringValue2, myDic[field1.field2]); 

// SomeFunction looks like this 
string SomeFunction (string string1, string string2, List<string> ra) 
{ 
    // method 
    return stringResult; 
} 
+2

什麼錯誤?它發生在哪裏? – mason

+1

你是什麼意思的「它的錯誤」?你會得到什麼錯誤?我的第一個猜測是'myDic [field1.field2]'失敗,因爲字典中沒有與'field1.field2'對應的鍵。 – germi

+0

如果'field1.field2'可能不在'myDic'中,那麼在使用它之前*測試*! – crashmstr

回答

2

根據意見更新。要通過,可能會或可能不存在,你可以做一個鍵(假設值是一個列表):

// assuming the method we are calling is defined like this: 
// public String SomeFunction(string string1, String string2, List<String> ra) 

List<string> valueToPassOn; 
if (_ra.ContainsKey(lc.Lc)) 
{ 
    valueToPassOn = _ra[lc.Lc] 
} 
else 
{ 
    valueToPassOn = new List<string>(); 
} 

string text = tooltip.SomeFunction(something1, something2, valueToPassOn); 

如果你想傳遞一個整個詞典(因爲這個問題本來讀),無論是否不存在字典:

你有兩個選擇。無論是創建字典,無論是這樣的:

if (myDic == null) 
{ 
    // change var and var2 to the types of variable they should be, ex: 
    myDic = new Dictionary<string, List<string>>(); 
} 
string text = SomeFunction(stringValue1, stringValue2, myDic); 

,或者什麼可能是更好的選擇,在功能SomeFunction的聲明中加入詞典與默認的參數變量。只要確保你的函數知道如果字典爲空,該怎麼做。

string SomeFunction(string string1, string string2, Dictionary dictionary = null) 
{ 
    // method here 
} 
1

您可以檢查是否使用ContainsKey方法存在的關鍵,如果它不是你傳遞你想要一個default值:下面的代碼片段的

// replace default(string) with the value you want to pass 
// if the key doesn't exist 
var value = myDic.ContainsKey(field1.field2) ? myDic[field1.field2] : default(string); 
string text = SomeFunction(stringValue1, stringValue2, value); 
+0

非常感謝Selman22。這就是我想我需要的。去嘗試一下。 – cd300

1

用途之一,以檢查是否詞典空,並採取一些行動:

var x = new Dictionary<string, string>(); 

if (x.Any()) 
{ 
    //.... 
} 

if (x.ContainsKey("my key")) 
{ 

} 

if (x.ContainsValue("my value")) 
{ 

} 

if (x.Count > 0) 
{ 

} 
1

你需要做的是確保字典實際上包含字典中給定的鍵。

如果需要通過按鍵來提取值,使用TryGetValue方法:

string value; 
if (myDict.TryGetValue(key, out value)) 
{ 
    // Key exists in the dictionary, do something with value. 
} 
相關問題