I would like to create a safe sum extension method that would have the same syntax as the normal Sum.
This would be the syntax I’d like to use:
result = Allocations.SumIntSafe(all => all.Cost);
I use the Int.Maxvalue as a penalty value in my operations and two Int.MaxValue summed together returns a Int.Maxvalue.
This is my adding function:
public static int PenaltySum(int a, int b) { return (int.MaxValue - a < b) ? int.MaxValue : a + b; }
Any ideas ?
EDIT:
I would like to use this function on generic collections of objects that have the value to be summed in different properties:
ie
all.SumInt32Safe(all => all.cost); days.SumInt32Safe(day => day.penalty);
Simplest way of doing it:
Btw, PenaltySum fails IMO: PenaltySum(-1, 0) returns int.MaxValue.
EDIT: With the changed requirements, you just want:
Or call
source.Select(x => x.Cost).SumInt32Safe();in the first place…