林克集团两次

时间:2015-03-10 09:18:41

标签: c# linq

我们有一项调查。我有一个模型如下:

Survey
    City 
    Satisfaction
    Id

满意度如下:

Satisfaction: 
    VerySatisfied, 
    Satisfied
    Undecided, 
    NotSatisfied

我对按城市分组感兴趣,然后我想通过非常满意和满意的分组。

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

我可以按城市分组,但我需要找到城市内的满意度。

即:纽约:%90%。

我如何分组两次以获得上述结果?

1 个答案:

答案 0 :(得分:6)

你可以试试这个:

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