How can I make sure that FirstOrDefault has returned a value

后端 未结 3 1202
没有蜡笔的小新
没有蜡笔的小新 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<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");
    }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-24 05:02

    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 or day could be a null.
    • 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
    0 讨论(0)
提交回复
热议问题