這裏是什麼,我試圖做一個簡化版本:我怎樣才能確保FirstOrDefault <KeyValuePair>返回一個值
var days = new Dictionary<int, string>();
days.Add(1, "Monday");
days.Add(2, "Tuesday");
...
days.Add(7, "Sunday");
var sampleText = "My favorite day of the week is 'xyz'";
var day = days.FirstOrDefault(x => sampleText.Contains(x.Value));
由於「XYZ」是不存在的KeyValuePair變量中, FirstOrDefault方法不會返回有效的值。我希望能夠檢查這種情況,但我意識到我無法將結果與「null」進行比較,因爲KeyValuePair是一個結構體。下面的代碼是無效的:
if (day == null) {
System.Diagnotics.Debug.Write("Couldn't find day of week");
}
我們試圖編譯代碼時,Visual Studio將引發以下錯誤:
Operator '==' cannot be applied to operands of type 'System.Collections.Generic.KeyValuePair<int,string>' and '<null>'
我如何檢查FirstOrDefault已返回一個有效的價值?
你有一個錯誤,但我認爲這是一個複製粘貼的東西:天是不是一個列表,你不能使用KeyValuePair的添加。 – Kobi 2009-08-26 16:46:03
ooops ...你是對的我從記憶中打字,我明顯犯了一個錯誤。感謝您指出。 – desautelsj 2009-08-30 04:39:01
這可能是:var days = new字典(); –
2010-08-03 18:35:31