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())

error message

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.)

Leave a Reply