Hi,
In the Linq query below, values is an array of double.
Could some please translate this VB.Net Linq query into C#:
Dim Aggreg = Aggregate v In values _
Into Count(), _
Sum(), _
Sum_Of_Squares = Sum(v * v)
Thank you,
Scott
Loading
Subhendu DePosted Dec 13, 2010, 4:34 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.....
S LemenPosted Dec 11, 2010, 7:24 PM
Thank you for your help with the translating the Linq query. However, I have a further question or observation.
There is a problem with part of the query. The Sum_of_Squares does not yield the correct result. The value of the double ret after the foreach loop does not equal the Aggreg.Sum_Of_Squares but it shoud. Code:
double[] values = { 2.2, 2.3, 3.3, 4.1, 5.6 };
double ret;
var Aggreg = new
{
Count = (from v in values
select v).Count(),
Sum = (from v in values
select v).Aggregate((cnt, v) => cnt += v),
Sum_Of_Squares = (from v in values
select v).Aggregate((cnt, v) => cnt += (v * v))
};
foreach (double v in values)
{
ret += (v * v);
}
ret = 69.19 but Aggreg.Sum_Of_Squares = 66.55.
I don't know why they are not equal.
Thank you for your help,
Regards,
Scott
Subhendu DePosted Dec 11, 2010, 11:32 AM
I hope the solution works for you. If yes, then please accept the answer and if not, then let me know. It will help community people to concentrate on other unanswered threads rather than answered threads. It was just a suggestion and not a big deal.
Thanks.....
S LemenPosted Dec 11, 2010, 11:20 AM
Scott
Subhendu DePosted Dec 11, 2010, 4:57 AM
var Aggreg = new
{
Count = (from v in values
select v).Count(),
Sum = (from v in values
select v).Aggregate((cnt, v) => cnt += v),
Sum_Of_Squares = (from v in values
select v).Aggregate((cnt, v) => cnt += (v * v))
};
Thanks.....