DarthVader
DarthVader

Reputation: 55022

linq group by twice

We have a survey. and I have a model as follows:

Survey
    City 
    Satisfaction
    Id

Satisfaction is an enum as follows:

Satisfaction: 
    VerySatisfied, 
    Satisfied
    Undecided, 
    NotSatisfied

I am interested in grouping by city and then I want to group by VerySatisfied and satisfied.

 var result= _db.Surveys.AsNoTracking()
    .GroupBy(x => x.City)
    .Select(group => new { 
        City = group.Key.Code, 
        CityName = group.Key.Name, 
        Count = group.Count() 
     })
    .OrderByDescending(x => x.Count);

I can do group by City, but I need to find the Satisfaction ratio within the city.

ie: New York: %90 percent.

How can i group by twice to get the result above?

Upvotes: 2

Views: 5110

Answers (1)

Farhad Jabiyev
Farhad Jabiyev

Reputation: 26635

You can try this:

var result= _db.Surveys.AsNoTracking()
               .GroupBy(x => x.City)
               .Select(group => new 
                      {
                            City = group.Key.Code, 
                            CityName = group.Key.Name, 
                            Count = group.Count(),
                            SatisfactionRatio = (group.Count(y => y.Satisfaction == Satisfaction.VerySatisfied || y.Satisfaction == Satisfaction.Satisfied) * 100) / group.Count()
                      })
               .OrderByDescending(x => x.Count);

Upvotes: 6

Related Questions