18

私はすべてを見てきましたが、これを理解することはできません。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;
4

4 に答える 4

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

Aggregate は、2 つの BigInteger を取得して BigInteger を返すメソッドへのデリゲートを取得します。デフォルトの BigInteger を初期値 (0) として使用し、各 BigInteger を調べて、前の結果 (0 は初回の前の結果 - 「シード」とも呼ばれる) と現在の要素で BigInteger.Add を呼び出します。

于 2012-04-21T05:20:19.270 に答える
12

集計関数は Sum のより一般的なバージョンです。

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

var result = bigInts.Aggregate((currentSum, item)=> currentSum + item));
于 2012-04-21T05:02:00.743 に答える
1

汎用リストでForEach()メソッドを使用して、追加を行うこともできます。

var bigInts = new List<BigInteger>();

BigInteger sum = 0;
bigInts.ForEach(x => sum += x);
于 2012-04-21T05:14:41.313 に答える
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を参照してください。

于 2012-04-21T05:12:37.617 に答える