I would like to create a safe sum extension method that would have the same syntax as the normal Sum.
我想创建一个安全的和扩展方法,它具有与普通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
.
我在我的操作中使用Int.Maxvalue作为惩罚值,并且两个Int.MaxValue相加在一起返回一个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);
2 个解决方案
#1
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.
顺便说一句,PenaltySum失败IMO:PenaltySum(-1,0)返回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...
或者调用source.Select(x => x.Cost).SumInt32Safe();首先...
#2
There is already an extension method that will help you out: Aggregate
已有一种扩展方法可以帮助您:聚合
all.Aggregate(PenaltySum);
#1
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.
顺便说一句,PenaltySum失败IMO:PenaltySum(-1,0)返回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...
或者调用source.Select(x => x.Cost).SumInt32Safe();首先...
#2
There is already an extension method that will help you out: Aggregate
已有一种扩展方法可以帮助您:聚合
all.Aggregate(PenaltySum);