2012-04-21 178 views
12

我已經看遍了所有,但無法弄清楚這一點。你如何總結一個BigIntegers列表?總結一個BigIntegers列表

Using System.Numerics; 
Using System.Linq; 

List<BigInteger> bigInts = new List<BigInteger>(); 
BigInteger sum = bigInts.Sum();    // doesn't work 
BigInteger sum = bigInts.Sum<BigInteger>(); // doesn't work 
BigInteger sum = bigInts.Sum(x => x);  // doesn't work 

你必須這樣做嗎?

BigInteger sum = new BigInteger(0); 
foreach(BigInteger bigint in bigInts) 
    sum += bigint; 

回答

7

Aggregate功能總和的更一般的版本:

var bigInts = new List<System.Numerics.BigInteger>(); 
bigInts.Add(new System.Numerics.BigInteger(1)); 

var result = bigInts.Aggregate((currentSum, item)=> currentSum + item)); 
+7

或者只是'bigInts.Aggregate(BigInteger.Add)':) – leppie 2012-04-21 05:15:22

+0

阿列克謝,這正是我在您提出答案後儘快使用的,我查了一下如何使用Aggregate。 @leppie,你能否添加一些解釋你的魔法是如何運作的? – 2012-04-21 05:21:34

+0

@jb .:它只是一個委託,引用'BigInteger.Add'方法。 – leppie 2012-04-21 05:22:49

0

正如阿列克謝說骨料是總和的比較一般。 下面介紹的是一種擴展方法。

public BigInteger static Sum(IEnumerable<BigInteger> this lst) 
{ 
    return lst.Aggregate(BigInteger.Zero, (acc, next)=> acc.Add(next)); 
} 

我還沒有測試過這個,我的C#可能會變得有點生疏。 但這個想法應該是聲音: 看到http://msdn.microsoft.com/en-us/library/bb549218.aspx#Y0

+1

你可能想要一個返回類型並返回一些東西。 – leppie 2012-04-21 05:13:34

+0

哦,我看到,當我打字@Alexei Levenkov時,更新了他的答案,以舉一個例子。 偉大的思想似乎 – 2012-04-21 05:13:42

+0

嬉皮,啊是的。太多使用F#的我。忘了那些。現在修復了 – 2012-04-21 05:15:10

0

您也可以使用泛型列表的ForEach()方法做加法:

var bigInts = new List<BigInteger>(); 

BigInteger sum = 0; 
bigInts.ForEach(x => sum += x); 
+0

我想到了這一點,但它仍然需要一個額外的BigInteger。如果我在'IEnumerable '中,我必須執行'.ToList()'。 (這是我的,但忘了提及) – 2012-04-21 05:19:35

+0

啊,那麼,這有點不同。 ( - : – 2012-04-21 05:23:27

11
var sum = bigInts.Aggregate(BigInteger.Add); 

聚合得到的委託,向四周兩種方法BigIntegers並返回一個BigInteger。它使用一個默認的BigInteger作爲初始值(0),並遍歷每個BigInteger,用前一個結果調用BigInteger.Add(0將是第一次結果 - 也稱爲'seed')和當前元素。

+0

Yorye!歡迎回來!:) – 2012-04-21 05:22:10

+0

大聲笑。同樣地!你現在有什麼問題? ; P – SimpleVar 2012-04-21 05:23:14

+0

處理「Add」時,初始值並不是真的必要。 – leppie 2012-04-21 05:23:29