Aggregate and foreach return different values
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);
}
CrishPosted Dec 14, 2010, 6:00 AM
I had same problem.thanks for code it will help me to solve the problem of Aggregate and foreach return different values.
Subhendu DePosted Dec 13, 2010, 4:32 AM
Sorry for delay response. I was working on it. During solving this issue, I found a difference between SUM And AGGREGATE.
Aggregate --> Returns a custom aggregate of the specified expression, as defined by the data provider.
Sum --> Returns the sum of all the non-null numeric values specified by the expression, evaluated in the given scope.
For your solution, I prefer to use SUM instead of AGGREGATE. I was more aligned to use AGGREGATE because my motive is to transform your VB.NET code to equivalent C#.
Double[] values = new Double[] { 2.2, 2.3, 3.3, 4.1, 5.6 };
var Aggreg = new
{
Count = (from v in values
select v).Count(),
Sum = (from v in values
select v).Sum(v => v),
Sum_Of_Squares = (from v in values
select v).Sum(v=>Math.Pow(v,2))
};
Console.WriteLine(Aggreg.Count);
Console.WriteLine(Aggreg.Sum);
Console.WriteLine(Aggreg.Sum_Of_Squares);
Reference Page -> http://msdn.microsoft.com/en-us/library/ms159673%28v=SQL.100%29.aspx
Please mark this as answer if it serves your query.
Thanks.....