Note that there are some explanatory texts on larger screens.

plurals
  1. POCalculate average with linq without grouping
    primarykey
    data
    text
    <p>I have a datatable, wich contains a several columns. I want to calculate the average of these with linq, without grouping: I tried this:</p> <pre><code>dtPointCollFb.GroupBy(r =&gt; 1).Select(r =&gt; new { Plus100 = r.Average(item =&gt; item.PLUS100), Plus50 = r.Average(item =&gt; item.PLUS50), Plus10 = r.Average(item =&gt; item.PLUS10), Plus5 = r.Average(item =&gt; item.PLUS5), Plus1 = r.Average(item =&gt; item.PLUS1), NULLA = r.Average(item =&gt; item.NULLA) }).ToList() </code></pre> <p>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.</p> <p>But without this i can't use average just for the whole query, and only for one column:</p> <pre><code>dtPointCollFb.Average(r =&gt; r.PLUS100) </code></pre> <p>So can someone produce a simple best practice solution? If it's possible with method syntax, not query.</p> <p>I want something like this:</p> <pre><code>dtPointCollFb.GroupBy(r =&gt; 0).Select(r =&gt; new { Plus100 = r.Sum(item =&gt; item.PLUS100) / dtPointCollFb.Rows.Count, Plus50 = r.Sum(item =&gt; item.PLUS50) / dtPointCollFb.Rows.Count, Plus10 = r.Sum(item =&gt; item.PLUS10) / dtPointCollFb.Rows.Count, Plus5 = r.Sum(item =&gt; item.PLUS5) / dtPointCollFb.Rows.Count, Plus1 = r.Sum(item =&gt; item.PLUS1) / dtPointCollFb.Rows.Count, NULLA = r.Sum(item =&gt; item.NULLA) / dtPointCollFb.Rows.Count }).ToList() </code></pre> <p>but with simpler and cleaner way. This produce the average correctly.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload