How can I make sure that FirstOrDefault has returned a value

后端 未结 3 1204
没有蜡笔的小新
没有蜡笔的小新 2020-12-24 04:14

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

var days = new Dictionary();
days.Add(1, \"Monday\");
days.Add(2, \"Tuesday\");
..         


        
3条回答
  •  再見小時候
    2020-12-24 04:52

    You can do this instead :

    var days = new Dictionary();   // 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");
    }
    

提交回复
热议问题