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

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

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

最佳答案

听起来您应该从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(),
                       });

关于c# - 在LINQ中按子表分组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18455428/

10-10 10:33