S Lemen

S Lemen

  • NA
  • 7
  • 15.7k

Aggregate and foreach return different values

Dec 12 2010 1:59 PM

Hi,
In the code below, the Linq aggregate Agg.Sum_Of_Squares and the double ret, after the foreach loop, have different values.  Agg.Sum_Of_Squares = 66.55 but ret = 69.19.  Should not both statements return the same value?
Thank you,
Scott

double ret = 0;
double[] values = { 2.2, 2.3, 3.3, 4.1, 5.6 };
var Agg = new
{
        Sum_Of_Squares = (
from v in values
         select v).Aggregate((cnt, v) => cnt += (v * v))
};
foreach (double v in values)
{
       ret += (v * v);
}

Answers (2)