2009-01-08 19 views
0

我想創建一個安全的總和擴展方法,它的語法與正常的總和相同。你將如何創建一個安全的int總和IList擴展?

這將是我想使用的語法:

result = Allocations.SumIntSafe(all => all.Cost); 

我用相加返回Int.MaxvalueInt.Maxvalue在我操作的懲罰值和兩個Int.MaxValue

這是我加入的功能:

public static int PenaltySum(int a, int b) 
{ 
    return (int.MaxValue - a < b) ? int.MaxValue : a + b; 
} 

任何想法?

編輯:

我想用在具有價值在不同的屬性來概括對象的泛型集合此功能:

all.SumInt32Safe(all => all.cost); 

days.SumInt32Safe(day => day.penalty); 
+0

您滿意的IList 代替非泛型的IList? – 2009-01-08 15:18:00

回答

1

最簡單的方法:

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

順便說一句,PenaltySum IMO失敗:PenaltySum(-1,0)返回int.MaxValue。

編輯:隨着改變的要求,你只是想:

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

或致電擺在首位source.Select(x => x.Cost).SumInt32Safe(); ...

1

已經有一個可以幫助你的擴展方法:Aggregate

all.Aggregate(PenaltySum); 
這樣做的
+0

這將如何處理我需要總結成本的事實? – 2009-01-08 15:42:25

+0

你說你想要一個Sum擴展方法,並且PenaltySum是你的添加函數。這將對所有的值運行PenaltySum並返回結果 – JaredPar 2009-01-08 16:16:30

相關問題