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 DeRank #1,108 · 1.7K reputationPosted Dec 10, 2010, 11:57 PM EST
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.....
S Lemen7 reputationPosted Dec 11, 2010, 6:20 AM EST
Scott
Subhendu DeRank #1,108 · 1.7K reputationPosted Dec 11, 2010, 6:32 AM EST
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 Lemen7 reputationPosted Dec 11, 2010, 2:24 PM EST
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 DeRank #1,108 · 1.7K reputationPosted Dec 12, 2010, 11:34 PM EST
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.....