Linq group by with sub grouping

时间:2015-02-24 16:28:46

标签: c# linq

我在使用LINQ完成此任务时遇到了一些麻烦。 Haven没有太多的经验 我有以下信息: 学校,考试,老师,学生

我需要计算每个考试的学校数量和教师数量,但我只需要计算教师在该考试中有超过10名学生的情况。

这是SQL:

select 
   test, 
   count(distinct school) school_count, 
   count(distinct teacher) teacher_count 
from 
  (select 
     test, 
     teacher, 
     school 
  from list 
  group by 
     test, 
     school, 
     teacher
  having 
     count(teacher) > 10) a 
group by a.test

我的结构非常简单。一类(不是实际代码)

class tests
{
public string teacher;
public string test;
public string school;
public string studentid;
}

然后我有一个我正在查询的测试列表 }

2 个答案:

答案 0 :(得分:0)

Linq中wherehaving之间没有区别。您可以执行以下操作:

void Tests(IEnumerable<tests> tests)
{
    var result =
        from t in tests.Select(t => new {Teacher = t.teacher, Test = t.test, School = t.school}).Distinct()
        group t by t.Test
        into g
        where g.Select(t => t.Teacher).Distinct().Count() > 10
        select new
        {
            Test = g.Key,
            TeacherCount = g.Select(t => t.Teacher).Distinct().Count(),
            SchoolCount = g.Select(t => t.School).Distinct().Count()
        };

}

附注:您的数据库结构可能需要normalization,您的命名约定不是recommended

答案 1 :(得分:0)

    var initial_group = from st in this                            group st by new {  st.TestName, st.School, st.Teacher }
                            into testGroups
                            where testGroups.Count() > 10
                            select new
                            {
                                Test = testGroups.Key.TestName,
                                School = testGroups.Key.School,
                                Teacher = testGroups.Key.Teacher,
                                Items = testGroups
                            };

    var results = from grp in initial_group
                  group grp by grp.Test
                      into testGroups

                      select new
                          {
                              Test = testGroups.Key,
                              NumSchools = testGroups.Select(a => a.School).Distinct().Count(),
                              NumTeachers = testGroups.Select(a => a.Teacher).Distinct().Count()
                          };

这很有效,但它看起来并不太优雅。能够将两个查询组合起来会很高兴。