Sum a list of BigIntegers

那年仲夏 提交于 2019-12-06 17:19:52

问题


I've looked all over but can't figure this out. How do you sum a list of 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

Do you have to do this?

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

回答1:


Aggregate function is more general version of Sum:

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

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



回答2:


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

Aggregate gets a delegate to a method which gets two BigIntegers and return a BigInteger. It uses a default BigInteger as initial value (0), and goes over each BigInteger, invoking BigInteger.Add with the previous result (0 would be previous result in the first time - also called 'seed') and the current element.




回答3:


You can also use the ForEach() method on generic lists to do the addition:

var bigInts = new List<BigInteger>();

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



回答4:


As Alexei said Aggregate is the more general from of sum. Presented below is an extension method.

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

I haven't tested this, and my C# might be getting a little rusty. but the idea should be sound: see http://msdn.microsoft.com/en-us/library/bb549218.aspx#Y0



来源:https://stackoverflow.com/questions/10256351/sum-a-list-of-bigintegers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!