Enumerable.Aggregate error

Everything worked fine until a single-element sequence was passed to this function. The easiest way to play:

var sumOfSquares = Enumerable.Range(5, 1).Aggregate((s, i) => s + i*i);
// sumOfSquares == 5

I think this version of Aggregate should throw an exception if the sequence contains only one element. Am I right or are there some details that I missed?

+3
source share
4 answers

There is another overload where you can provide the right seed and get what you think is your desired outcome.

var sumOfSquares = Enumerable.Range(5, 1).Aggregate(0, (s, i) => s + i * i);

0 - , s - , i - . 25. (5, 2) 61, (5, 3) 110 ..

+4

. :

.

, (5), . .

, , . 0 25, , , .

var sumOfSquares = Enumerable.Range(5, 1).Aggregate(0, (s, i) => s + i * i);

, , Aggregate - Sum.

var sumOfSquares = Enumerable.Range(5, 1).Sum(i => i * i);

, .

+7

? .

, , - :

public double MySum(IEnumerable<double> seq) {
    switch (seq.Count()) {
        case 0: return 0.0;
        case 1: return seq.First();
        default: return seq.Aggregate((s, i) => s + i);
    }
}

, (, , ).

0

(. Anthony Pegram ), Aggregate IEnumerable . , - IEnumerable, ? , Aggregate . , :

var c = 0;
var result = Enumerable.Range(5,1).Aggregate((acc,x) => acc + (x / c));
//result == 5

Change this to Enumerable.Range(5,2)and it will immediately throw a divide by zero error.

Link : msdn in the Remarks section

0
source

Source: https://habr.com/ru/post/1780742/


All Articles