2

我有学生表和科目表,我需要按科目对学生进行分组。我尝试了以下不显示 s.StudentSubjects.SubjectName 。如何使用子表编写 group by 。

学生 -> 学生 ID | 名称
StudentSubjects -> SubjectID | 学生证 | 主题名称

        var list = from s in students
                   group s by s.StudentSubjects.? into g
                   select new StudentSubjectsCounts
                   {
                       Name = g.Key,
                       Count = g.Count(),                           
                   };
4

2 回答 2

2

听起来你应该查询StudentSubjects而不是Student

var list = from ss in studentSubjects
           group ss by s.SubjectName into g
           select new StudentSubjectsCounts
           {
               Name = g.Key,
               Count = g.Count(),                           
           };

或者,从学生列表开始:

var list = students.SelectMany(s => s.StudentSubjects)
                   .GroupBy(ss => ss.SubjectName)
                   .Select(g => new StudentSubjectsCounts
                       {
                           Name = g.Key,
                           Count = g.Count(),                           
                       });
于 2013-08-27T01:27:13.377 回答
1

您应该能够按StudentSubject对象本身进行分组

var list = from s in students
           group s by s.StudentSubjects into g
           select new StudentSubjectsCounts
           {
               Name = g.Key.SubjectName,
               Count = g.Count(),                           
           };

但如果您不想这样做,请使用Select

var list = from s in students
           group s by s.StudentSubjects.Select(ss => ss.SubjectName) into g
           select new StudentSubjectsCounts
           {
               Name = g.Key,
               Count = g.Count(),                           
           };
于 2013-08-27T01:22:33.977 回答