I have a datatable, wich contains a several columns. I want to calculate the average of these with linq, without grouping: I tried this:
dtPointCollFb.GroupBy(r => 1).Select(r => new
{
Plus100 = r.Average(item => item.PLUS100),
Plus50 = r.Average(item => item.PLUS50),
Plus10 = r.Average(item => item.PLUS10),
Plus5 = r.Average(item => item.PLUS5),
Plus1 = r.Average(item => item.PLUS1),
NULLA = r.Average(item => item.NULLA)
}).ToList()
This works perfectly, when I calculate Sum, but with average produce the first record values, not all records' average. I think this is unnecessary: .GroupBy(r => 1) because I'm grouping with constant.
But without this i can't use average just for the whole query, and only for one column:
dtPointCollFb.Average(r => r.PLUS100)
So can someone produce a simple best practice solution? If it's possible with method syntax, not query.
I want something like this:
dtPointCollFb.GroupBy(r => 0).Select(r => new
{
Plus100 = r.Sum(item => item.PLUS100) / dtPointCollFb.Rows.Count,
Plus50 = r.Sum(item => item.PLUS50) / dtPointCollFb.Rows.Count,
Plus10 = r.Sum(item => item.PLUS10) / dtPointCollFb.Rows.Count,
Plus5 = r.Sum(item => item.PLUS5) / dtPointCollFb.Rows.Count,
Plus1 = r.Sum(item => item.PLUS1) / dtPointCollFb.Rows.Count,
NULLA = r.Sum(item => item.NULLA) / dtPointCollFb.Rows.Count
}).ToList()
but with simpler and cleaner way. This produce the average correctly.