views:

236

answers:

2

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);

+1  A: 

There is already an extension method that will help you out: Aggregate

all.Aggregate(PenaltySum);
JaredPar
how will this deal with the fact that I need to sum over cost ?
Tomas Pajonk
You said you wanted a Sum extension method and that PenaltySum was your adding function. This will run PenaltySum over all of the values and return the result
JaredPar
+1  A: 

Simplest way of doing it:

public static int SumInt32Safe(this IList<int> source)
{
    long sum = source.Sum(x => (long) x);
    return (int) Math.Max(sum, (long) int.MaxValue);
}

Btw, PenaltySum fails IMO: PenaltySum(-1, 0) returns int.MaxValue.

EDIT: With the changed requirements, you just want:

public static int SumInt32Safe<T>(this IList<T> source, Func<T, int> selector)
{
    long sum = source.Sum(x => (long) selector(x));
    return (int) Math.Max(sum, (long) int.MaxValue);
}

Or call source.Select(x => x.Cost).SumInt32Safe(); in the first place...

Jon Skeet
That is OK. Negative numbers are not allowed as penalties.
Tomas Pajonk