0
我试图用下面显示的数据得到以下结果。我不知道如何使用linq group来实现结果。任何人都可以请帮助如何解决这个问题?我正在使用EntityFramework来获取实体。C#linq groupby与多对多表记录
public class Student
{
public long StudentId { get; set; }
public string Name { get; set; }
public virtual ICollection<StudentCourse> Courses { get; set; }
}
public class Course
{
public long CourseId { get; set; }
public string Name { get; set; }
public virtual ICollection<StudentCourse> Students { get; set; }
}
public class StudentCourse
{
public virtual long StudentId { get; set; }
public virtual Student Student { get; set; }
public virtual long CourseId { get; set; }
public virtual Course Course { get; set; }
public string Location { get; set; }
}
示例数据:
Student
-------
StudentId Name
8 Stud8
Course:
------
CourseId Name
88 Course88
148 Course148
196 Course196
453 Course453
StudentCourse: (StudentId + CourseId + Location makes the uniqueness)
------------
StudentId CourseId Location
8 88 Location 88
8 88 Location 89
8 148 Location 148
8 196 Location 196
8 453 Location 453
Expected Result for StudentId 8:
CourseId Name Location
-------- ----- -------
88 Course88 Location 88
88 Course88 Location 89
148 Course148 Location 148
196 Course196 Location 196
453 Course453 Location 453
如上述例子所示,课程可以重复不同的位置。
如何使用C#linq group by得到上述结果。我试过以下内容:
var courses = context.courses.Select(g => new
{
Course = g,
Location = g.Students.FirstOrDefault(m => m.StudentId == studentId).Location,
});
but i am not getting the right course for the same recipe.
以下代码适用于我。但想知道是否有更好的方法来做到这一点。我加入的附加项目
var existingStudentCourses = new List<Model.Entity.StudentCourse>();
var result = new List<CustomClass>();
foreach(var item in context.courses)
{
var studentCourses = item.Students.Where(x=>x.StudentId == studentId && !existingStudentCourses.Any(y=>y.Equals(x)));
var studentCourse = studentCourses.FirstOrDefault();
existingStudentCourses.Add(studentCourse);
result.Add(new CustomClass
{
Course = item,
Location = studentCourse.Location
});
}
感谢