views:

116

answers:

1

I have a groupby that I groups all elements. I can see the items are there in LinqPad but can't find a way to get the count.

Here is what I have so far:

SurveyResponses.Where( q => q.QuestionId == 4).GroupBy(q => q.AnswerNumeric).Where( g => g.Key == 1)

In Linq Pad I can see there are 4 items in this query. If I do Count it returns 1. I've tried, ToList().Count, Select(x => x).Count, etc.

To be clear, I have an IGrouping and need to get the count from it.

+2  A: 

In the code you posted you don't have an IGrouping<int, Response>, you have an IEnumerable<IGrouping<int, Response>>. You are counting the number of groupings that fulfil the Where predicate.

Use Single instead of Where to get the result you expect:

int count = SurveyResponses
    .Where(q => q.QuestionId == 4)
    .GroupBy(q => q.AnswerNumeric)
    .Single(g => g.Key == 1)
    .Count();
Mark Byers