How would you create a safe int int IList extension?
I would like to create a reliable sum extension method that will have the same syntax as normal Sum.
This will be the syntax I would like to use:
result = Allocations.SumIntSafe(all => all.Cost);
I use Int.Maxvalue
as the penalty value in my operations, and the two Int.Maxvalue
are added together.
This is my add 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 for generic collections of objects that can be summed up in different properties:
t
all.SumInt32Safe(all => all.cost);
days.SumInt32Safe(day => day.penalty);
0
source to share
2 answers
The simplest way to do 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 doesn't work IMO: PenaltySum (-1, 0) returns int.MaxValue.
EDIT: with 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();
first ...
+1
source to share