Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

linq Average within a groupby

In this sample below I would like to get the Average of the Answer Yes/No within a groupby. I am trying to get the count of Yes and the count of No and set the Average to PercentYes .

PercentYes = g.Average(g.Where(f => f.Answer == "Yes").Count(),g.Where(f => f.Answer == "No").Count())

https://dotnetfiddle.net/oyx6Ju

error message

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Compilation error (line 41, col 20): No overload for method 'Average' takes 2 arguments

>Solution :

Average indeed does not take two arguments. It doesn’t calculate an average of what you pass it, it calculates an average from what you call it on (in this case g), using an optional argument as a function to pull a specific value from each instance of the collection (each instance of g).

You may be over-thinking it. Not everything needs LINQ. You don’t even want an average. You want a percent. Just divide the "Yes" count by the total. For example:

var yesCount = (decimal)g.Count(f => f.Answer == "Yes");
var noCount = (decimal)g.Count(f => f.Answer == "No");
var percentYes = yesCount / (yesCount + noCount);

(Note: I’m casting the "count" values to decimal to avoid integer division, which would otherwise always result in 0 here.)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading