Safely dereferencing FirstOrDefault call in Linq c#

后端 未结 3 1041
谎友^
谎友^ 2021-02-12 22:08

For brevity\'s sake in my code, i\'d like to be able to do the following: having a collection, find the first element matching a lambda expression; if it exists, return the valu

3条回答
  •  鱼传尺愫
    2021-02-12 22:25

    I like this as an extension method:

    public static U SelectMaybe(this T input, Func func)
    {
        if (input != null) return func(input);
        else return default(U);
    }
    

    And usage:

    var UpperValueOfAString = stuff.FirstOrDefault(s => s.Contains("bvi")).SelectMaybe(x => x.ToUpper());
    var UpperValueOfAStringWannabe = stuff.FirstOrDefault(s => s.Contains("unknown token")).SelectMaybe(x => x.ToUpper());
    

    This will chain return the default value (null in this case, but as is correct for that type), or call the relevant function and return that.

提交回复
热议问题