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

Viewed 44765

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:

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:

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?

4 Answers

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

Select a list of valid values then check if it contains your day.Value; like this:

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

//check that FirstOrDefault has returned a valid value
if (days.Select(x=>x.Value).Contains(day.Value))
{
    //VALID
}
else
{
    System.Diagnostics.Debug.Write("Couldn't find day of week");
}

Here's another example using a list of key value pairs:

var days = new List<KeyValuePair<int, string>>();
days.Add(new KeyValuePair<int, string>(1, "Monday"));
days.Add(new KeyValuePair<int, string>(1, "Tuesday"));
days.Add(new KeyValuePair<int, string>(1, "Sunday"));
var sampleText = "My favorite day of the week is 'xyz'";
var day = days.FirstOrDefault(x => sampleText.Contains(x.Value));

//check that FirstOrDefault has returned a valid value
if (days.Select(x => x.Value).Contains(day.Value))
{
    //VALID
}
else
{
    System.Diagnostics.Debug.Write("Couldn't find day of week");
}

Hope this helps someone!

Related