How can I make sure that FirstOrDefault has returned a value

后端 未结 3 1205
没有蜡笔的小新
没有蜡笔的小新 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:56

    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.

提交回复
热议问题