Sum a list of BigIntegers

筅森魡賤 提交于 2019-12-04 22:56:12

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

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);
Lyndon White

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

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