A different take on FirstOrDefault

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

    Since this is an overload, it's worth mentioning the version with no predicate.

    public static T FirstOrValue(this IEnumerable sequence, T value)
    {
        if (sequence == null) throw new ArgumentNullException("sequence");
        foreach(T item in sequence) 
            return item; 
        return value;
    }
    

提交回复
热议问题