In some cases, yes (not always); and despite rumour to the contrary, it is possible. I wrote some code for "MiscUtil" (free, etc) that does exactly this, and which works for all types with suitable operators (even your own structs and classes, or Nullable<T>
, etc).
The problem here is that there is no interface that supports Add
etc, so until dynamic
comes along (in 4.0) it is tricky to do; but it can be done - here's the usage page, with a simiplfied Sum
(the actual code in "MiscUtil" is slightly more complex):
public static T Sum<T>(this IEnumerable<T> source)
{
T sum = Operator<T>.Zero;
foreach (T value in source)
{
if (value != null)
{
sum = Operator.Add(sum, value);
}
}
return sum;
}
Again, a lot of this is relatively simple in 4.0 with dynamic
, since this supports operators; however, last time I benchmarked it, dynamic
was slower than my (ab)use of Expression
.
As an aside, the reason that standard LINQ can provide a Min
/ Max
is because of IComparable
/IComparable<T>
, assisted by Comparer<T>.Default
.