2012-04-21 118 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