A different take on FirstOrDefault

前端 未结 4 1085
抹茶落季
抹茶落季 2021-02-20 14:39

The IEnumerable extension method FirstOrDefault didn\'t exactly do as I wanted so I created FirstOrValue. Is this a good way to go about this or is there a better way?



        
4条回答
  •  盖世英雄少女心
    2021-02-20 15:11

    default(T) will return null by default for reference types.

    I would do this

    public static T FirstOrValue(this IEnumerable source, Func predicate, T value)
    {
        T first = source.FirstOrDefault(predicate);
        return first ?? value;
    }
    

提交回复
热议问题