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
How can I make sure that FirstOrDefault<KeyValuePair> has returned a value
提问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
FirstOrDefault
doesn'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:
笔记:
- If your code is generic it is better to use
EqualityComparer<T>.Default.Equals(day, defaultDay)
, becuase.Equals
may be overridden orday
could be anull
. - In C# 7.1 you will be able to use
var defaultDay = default;
, see Target-typed "default" literal. - See also: Reference Source -
FirstOrDefault
- 如果您的代码是通用的,最好使用
EqualityComparer<T>.Default.Equals(day, defaultDay)
,因为.Equals
可能会被覆盖或day
可能是null
. - 在 C# 7.1 中,您将能够使用
var defaultDay = default;
,请参阅目标类型的“默认”文字。 - 另见:参考来源 -
FirstOrDefault
回答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");
}