Code factorization with delegate
I want to write an extension method Sum on IEnumerable<int> and an extension method Sum on IEnumerable<decimal>.
public static int Sum(this IEnumerable<int> source)
{
int value = 0;
foreach (int item in source)
value += item;
return value;
}
public static decimal Sum(this IEnumerable<decimal> source)
{
decimal value = 0;
foreach (decimal item in source)
value += item;
return value;
}
Now I want to factorize this code but the problem is: how to factorize the initialization (= 0 with an int and = 0 with a decimal) and the addition? To do this, we can use delegate:
private static T Sum<T>(this IEnumerable<T> source, Func<T, T, T> addition)
{
T value = default(T);
foreach (T item in source)
value = addition(value, item);
return value;
}
public static int Sum(this IEnumerable<int> source)
{
return source.Sum((i1, i2) => i1 + i2);
}
public static decimal Sum(this IEnumerable<decimal> source)
{
return source.Sum((d1, d2) => d1 + d2);
}
In this case, we can replace the foreach loop by an Aggregate:
private static T Sum<T>(this IEnumerable<T> source, Func<T, T, T> addition)
{
return source.Aggregate(default(T), (elt1, elt2) => addition(elt1, elt2));
}