最佳答案
下面是我正在尝试做的事情的一个简化版本:
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”,FirstOrDefault 方法将不返回有效值。我希望能够检查这种情况,但是我意识到我不能将结果与“ null”进行比较,因为 KeyValuePair 是一个 struc。下列代码无效:
if (day == null) {
System.Diagnotics.Debug.Write("Couldn't find day of week");
}
如果您尝试编译代码,VisualStudio 将引发以下错误:
Operator '==' cannot be applied to operands of type 'System.Collections.Generic.KeyValuePair<int,string>' and '<null>'
如何检查 FirstOrDefault 是否返回了有效值?