A different take on FirstOrDefault

前端 未结 4 1146
抹茶落季
抹茶落季 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:14

    Seems reasonable to me if you want to tweak the readability instead of using DefaultIfEmpty.

    You could also create an override that uses a lambda if the creation of the default value is expensive, creating it only if necessary.

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

提交回复
热议问题