我怎样才能确保FirstOrDefault< KeyValuePair>返回值 [英] How can I make sure that FirstOrDefault<KeyValuePair> has returned a value

查看:228
本文介绍了我怎样才能确保FirstOrDefault< KeyValuePair>返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里是什么我试图做一个简化版本:

Here's a simplified version of what I'm trying to do:

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方法将不会返回一个有效的值。我希望能够检查对于这种情况,但我知道我不能比较的结果为空,因为KeyValuePair是一个STRUC。下面的代码是无效的:

Since 'xyz' is not present in the KeyValuePair variable, the FirstOrDefault method will not return a valid value. I want to be able to check for this situation but I realize that I can't compare the result to "null" because KeyValuePair is a struc. The following code is invalid:

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

我们试图编译代码时,Visual Studio引发以下错误:

We you attempt to compile the code, Visual Studio throws the following error:

Operator '==' cannot be applied to operands of type 'System.Collections.Generic.KeyValuePair<int,string>' and '<null>'

我如何检查FirstOrDefault已返回一个有效的值

How can I check that FirstOrDefault has returned a valid value?

推荐答案

这是我认为最简洁明了的方式:

This is the most clear and concise way in my opinion:

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

这用怪异的默认值的东西对于结构完全得到周围。

This completely gets around using weird default value stuff for structs.

这篇关于我怎样才能确保FirstOrDefault&LT; KeyValuePair&GT;返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆