在LINQ中按子表分组

时间:2013-08-27 01:15:00

标签: c# .net linq entity-framework

我有学生表,我有主题表,我需要按主题对学生进行分组。我尝试了以下哪些不显示s.StudentSubjects.SubjectName。如何用子表编写分组。

学生 - > StudentID |名称
StudentSubjects - > SubjectID | StudentID |主旨名称

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

2 个答案:

答案 0 :(得分: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(),                           
                       });

答案 1 :(得分: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(),                           
           };