I have the following where I want to handle null values in a specific way when fetching from db:
/// <summary>
/// Implemented this because the Linq Sum() method does not fit our requirements for handling null values:
/// 1. Empty or null source should return a null, not zero
/// 2. If non-empty, and all elements are null, then return null, not zero
/// 3. If non-empty, and some elements are null, ignore them
public static decimal? NullableSum(this IEnumerable<decimal?> source)
{
if (source == null || source.Count() == 0) return null;
decimal? sum = null;
foreach (var v in source)
{
if (v != null)
{
if (sum == null)
{
sum = 0;
}
sum += v;
}
}
return sum;
}
How can I genericize this?
|| source.Count() == 0like that. It causes completely unnecessary double enumeration. It can be removed and the code will act exactly the same (but be faster in some scenarios)..Countseparately would cause double evaluation of the DB query... with corresponding correctness and performance cost. (in most cases loosing some performance could be ok, but code that can't be correct is rarely useful)you mean remove || source.Count == 0 ?Yes.