C#linq groupby有很多表记录

时间:2016-12-01 13:56:04

标签: c#-4.0 linq-to-entities

我试图通过以下显示的数据获得以下结果。我不知道如何使用linq group by来实现结果。任何人都可以帮忙解决这个问题吗?我正在使用EntityFramework来获取实体。

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获取上述结果。我尝试过以下方法:

    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
            });
        }   

由于

1 个答案:

答案 0 :(得分:0)

你可以查询StudentCourses表吗?那么代码就是

midX

如果您必须使用课程表,可以尝试

midY