I would like to propose adding overloads to the System.Linq.Enumerable.*OrDefault and System.Linq.Queryable.*OrDefault methods for specifying the value to be returned in the default case. This is the value that would be returned instead of default(TSource) when there are no items in the enumeration
There are times when the default value of a given type may be a valid value from the enumeration. If the default value for the enumeration type is valid value, there is not a nice way to determine if the returned values was because the enumeration was empty or if that value was in the enumeration.
Proposed API change
namespaceSystem.Linq{publicstaticclassEnumerable{publicstaticTSourceSingleOrDefault<TSource>(thisIEnumerable<TSource>source,TSourcedefaultValue);publicstaticTSourceSingleOrDefault<TSource>(thisIEnumerable<TSource>source,Func<TSource,bool>predicate,TSourcedefaultValue);publicstaticTSourceFirstOrDefault<TSource>(thisIEnumerable<TSource>source,TSourcedefaultValue);publicstaticTSourceFirstOrDefault<TSource>(thisIEnumerable<TSource>source,Func<TSource,bool>predicate,TSourcedefaultValue);publicstaticTSourceLastOrDefault<TSource>(thisIEnumerable<TSource>source,TSourcedefaultValue);publicstaticTSourceLastOrDefault<TSource>(thisIEnumerable<TSource>source,Func<TSource,bool>predicate,TSourcedefaultValue);}publicstaticclassQueryable{publicstaticTSourceSingleOrDefault<TSource>(thisIQueryable<TSource>source,TSourcedefaultValue);publicstaticTSourceSingleOrDefault<TSource>(thisIQueryable<TSource>source,Func<TSource,bool>predicate,TSourcedefaultValue);publicstaticTSourceFirstOrDefault<TSource>(thisIQueryable<TSource>source,TSourcedefaultValue);publicstaticTSourceFirstOrDefault<TSource>(thisIQueryable<TSource>source,Func<TSource,bool>predicate,TSourcedefaultValue);publicstaticTSourceLastOrDefault<TSource>(thisIQueryable<TSource>source,TSourcedefaultValue);publicstaticTSourceLastOrDefault<TSource>(thisIQueryable<TSource>source,Func<TSource,bool>predicate,TSourcedefaultValue);}}Updates
- Switch from using default parameters to method overloads
- Added IQueryable methods as well
I would like to propose adding overloads to the System.Linq.Enumerable.*OrDefault and System.Linq.Queryable.*OrDefault methods for specifying the value to be returned in the default case. This is the value that would be returned instead of
default(TSource)when there are no items in the enumerationThere are times when the default value of a given type may be a valid value from the enumeration. If the default value for the enumeration type is valid value, there is not a nice way to determine if the returned values was because the enumeration was empty or if that value was in the enumeration.
Proposed API change
Updates