2009-08-26 166 views
66

這裏是什麼,我試圖做一個簡化版本:我怎樣才能確保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已返回一個有效的價值?

+1

你有一個錯誤,但我認爲這是一個複製粘貼的東西:天是不是一個列表,你不能使用KeyValuePair的添加。 – Kobi 2009-08-26 16:46:03

+0

ooops ...你是對的我從記憶中打字,我明顯犯了一個錯誤。感謝您指出。 – desautelsj 2009-08-30 04:39:01

+0

這可能是:var days = new字典(); – 2010-08-03 18:35:31

回答

42

這是我認爲最簡潔明瞭的方式:

var matchedDays = days.Where(x => sampleText.Contains(x.Value)); 
if (!matchedDays.Any()) 
{ 
    // Nothing matched 
} 
else 
{ 
    // Get the first match 
    var day = matchedDays.First(); 
} 

這完全得到周圍用怪異的默認值工具和結構。

+12

問題在於,有可能(取決於具體實現)枚舉日將被枚舉兩次,甚至更糟糕的是返回Any()和First()調用之間的不同值 – 2012-09-07 14:51:51

+0

@RayBooysen一個調用ToArray或ToList解決了這個問題,你可以使用Count/Length和Indexer。 – Console 2014-02-28 13:00:11

119

FirstOrDefault不返回空值,它返回default(T)
您應該檢查:

var defaultDay = default(KeyValuePair<int, string>); 
bool b = day.Equals(defaultDay); 

MSDN - Enumerable.FirstOrDefault<TSource>

default(TSource) if source is empty; otherwise, the first element in source.

注:

+11

+1,KeyValuePair是一個值類型(結構),而不是引用類型(類)或可爲null的值類型,因此它不能爲空。 – Lucas 2009-08-26 17:06:23

+0

謝謝,它真的工作! – desautelsj 2009-08-26 19:18:15

+0

缺少typeof運算符,但對於好東西仍然爲+1 – 2009-09-30 20:51:10

1

你可以這樣做,而不是:

var days = new Dictionary<int?, string>(); // replace int by int? 
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)); 

然後:

if (day.Key == null) { 
    System.Diagnotics.Debug.Write("Couldn't find day of week"); 
}