Get the cardinality in a Linq-to-sql GroupBy query?
I have a GroupBy that I am grouping all the elements. I can see the items are in LinqPad but can't find a way to get the score.
Here's what I have so far:
SurveyResponses.Where( q => q.QuestionId == 4)
.GroupBy(q => q.AnswerNumeric)
.Where( g => g.Key == 1)
In Linq Pad I see that there are 4 items in this query. If I do Count it returns 1.
I tried ToList().Count
, Select(x => x).Count
and so on
To be clear, I have IGrouping and need to get a counter.
a source to share
In the code you posted, no IGrouping<int, Response>
, you have IEnumerable<IGrouping<int, Response>>
. You count the number of groupings that match the predicate Where
.
Use Single
instead Where
to get the expected result:
int count = SurveyResponses
.Where(q => q.QuestionId == 4)
.GroupBy(q => q.AnswerNumeric)
.Single(g => g.Key == 1)
.Count();
a source to share