如何组合来自两个通用列表的数据并将该合并指定为DataGridView的数据源?

时间:2016-03-10 06:04:20

标签: c# linq datagridview lambda generic-list

我有两个课程,AssignmentHistory和Students。我想在DataGridView中显示AssignmentHistory的内容,如下所示:

List<AssignmentHistory> assignmentHistory = AYttFMConstsAndUtils.AssignmentHistList
    .OrderBy(s => s.StudentID_FK).ThenBy(w => w.WeekOfAssignment).ToList();
dataGridViewStudentHistory.DataSource = assignmentHistory;

但是AssignmentHistory类只有一个StudentID,而不是一个名字;名称在Student类中。我可以这样得到它:

Student student = StudentsList.FirstOrDefault(s => s.StudentID == studentId);
string fullName = $"{student.firstName} {student.lastName}";

(Student.StudentID对应于AssignmentHistory.StudentID_FK)

如何用全名替换ID,以便它显示在DataGridView?

更新

它似乎并不想要&#34;包括&#34 ;;我试过&#34; Union&#34;但那也不起作用:

List<AssignmentHistory> assignmentHistory = AYttFMConstsAndUtils.AssignmentHistList
                .Union(AYttFMConstsAndUtils.StudentsList)
                .OrderBy(s => s.StudentID_FK).ThenBy(w => w.WeekOfAssignment).ToList();

当我这样做时,&#34; s。&#34;在OrderBy中不允许任何AssignmentHistList或StudentsList的成员。

更新2

我最终做的事情,至少是暂时的,是创建了第三个类,它将来自两种不同通用列表的我需要的数据组合在一起。我循环遍历assignmentHistory的内容,并在必要时通过以下代码获取我需要的值:

Student student = GetStudentForStudentId(ah.studentId);
string fullName = student.FullName;
newClass.FullName = fullName;

...等。然后我简单地使用新的,合并的通用列表,它由来自其他地方的零碎组成,作为DataGridView的数据源。

1 个答案:

答案 0 :(得分:1)

如果可以从AssignmentHistList的/ property访问学生

List<AssignmentHistory> assignmentHistory = AYttFMConstsAndUtils.AssignmentHistList
                                           .Include(x => x.Student)
                                           .OrderBy(s => s.Student.StudentId).ThenBy(w => w.WeekOfAssignment).ToList();

这将包括来自assignmenthistlist和student

的所有字段

但如果不是

List<AssignmentHistory> assignmentHistory = AYttFMConstsAndUtils.AssignmentHistList
                                       .Include(x => x.Student)
                                       .OrderBy(s => s.Student.StudentId)
                                       .ThenBy(w => w.WeekOfAssignment)
                                       .Select(x => 
            new { Field1 = x.field1, 
                  Field2 = x.field2..... 
                  StudentFirstName = StudentsList.Where(y => y.StudentId == x.AssignmentHistory.StudentID_FK).Select(c => c.FirstName).FirstOrDefault(),
                  StudentLastName = StudentsList.Where(y => y.StudentId == x.AssignmentHistory.StudentID_FK).Select(c => c.LastName).FirstOrDefault(),
                  StudentFullName = StudentsList.Where(y => y.StudentId == x.AssignmentHistory.StudentID_FK).Select(c => c.FirstName + " " + c.LastName).FirstOrDefault()}
.ToList();