-->

Sum a list of BigIntegers

2020-08-10 04:09发布

问题:

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