C# 如何确保 FirstOrDefault<KeyValuePair> 已返回值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1335419/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 15:17:16  来源:igfitidea点击:

How can I make sure that FirstOrDefault<KeyValuePair> has returned a value

c#linq

提问by desautelsj

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));

Since 'xyz' is not present in the dictionary, 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:

由于字典中不存在“xyz”,因此 FirstOrDefault 方法将不会返回有效值。我希望能够检查这种情况,但我意识到我无法将结果与“null”进行比较,因为 KeyValuePair 是一个结构体。以下代码无效:

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

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

我们尝试编译代码,Visual Studio 抛出以下错误:

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

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

如何检查 FirstOrDefault 是否返回了有效值?

采纳答案by Kobi

FirstOrDefaultdoesn't return null, it returns default(T).
You should check for:

FirstOrDefault不返回 null,它返回default(T).
您应该检查:

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

From MSDN - Enumerable.FirstOrDefault<TSource>:

MSDN -Enumerable.FirstOrDefault<TSource>

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

默认( TSource) 如果源为空;否则,source 中的第一个元素。

Notes:

笔记:

回答by peaceoutside

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.

这完全绕过了对结构使用奇怪的默认值的东西。

回答by Jocelyn Marcotte

You can do this instead :

你可以这样做:

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));

and then :

进而 :

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