How can I make sure that FirstOrDefault<KeyValuePair> has returned a value
FirstOrDefault
doesn't return null, it returns default(T)
.
You should check for:
var defaultDay = default(KeyValuePair<int, string>);
bool b = day.Equals(defaultDay);
From MSDN - Enumerable.FirstOrDefault<TSource>
:
default(TSource) if source is empty; otherwise, the first element in 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
KeyValuePair<int, string> defaultDay = default;
, see Target-typed "default" literal. - See also: Reference Source -
FirstOrDefault
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.