我正在尝试加入2个 LINQ 查询。但是根据我的愿望,我没有得到结果。
List<TeacherSubjectVM> query = (from t in uow.staffs
join ts in uow.teachersubjects on t.ID equals ts.teacherID
join s in uow.subjects on ts.subjectID equals s.ID
select new TeacherSubjectVM
{
subjectName = s.Name,
teacherName = t.fname,
}).ToList();
List<TeacherSubjectVM> query1 = (from t in uow.subjects
join ts in uow.classsubjects on t.ID equals ts.subjectID
join s in uow.jamats on ts.subjectID equals s.ID
select new TeacherSubjectVM
{
section = s.section,
className = s.name,
}).ToList();
List<TeacherSubjectVM> combine = query.Concat(query1).ToList();
班级名称和科目应与科目名称和教师姓名位于同一行:
答案 0 :(得分:1)
只需一步即可加入您想要加入的所有表格:
List<TeacherSubjectVM> query = (from t in uow.staffs
join ts in uow.teachersubjects on t.ID equals ts.teacherID
join s in uow.subjects on ts.subjectID equals s.ID
join cs in uow.classsubjects on ts.subjectID equals cs.ID
join j in uow.jamats on ts.subjectID equals j.ID
select new TeacherSubjectVM
{
subjectName = s.Name,
teacherName = t.fname,
section = cs.section,
className = j.name,
}).ToList();
我认为你正在尝试做的事情,但是变量名称和变量名称的重复使用使得它很难阅读。
答案 1 :(得分:0)
您正在采取的方法无法提供所需的方法,因为Concat
函数不会合并对象,它只会将query1
中的所有项目追加到query
中列表,这里combine
。
达到你的愿望是循环它们并手动合并对象,如下所示:
List<TeacherSubjectVM> query = (from t in uow.staffs
join ts in uow.teachersubjects on t.ID equals ts.teacherID
join s in uow.subjects on ts.subjectID equals s.ID
select new TeacherSubjectVM
{
Id = ts.subjectID,
subjectName = s.Name,
teacherName = t.fname,
}).ToList();
List<TeacherSubjectVM> query1 = (from t in uow.subjects
join ts in uow.classsubjects on t.ID equals ts.subjectID
join s in uow.jamats on ts.subjectID equals s.ID
select new TeacherSubjectVM
{
Id = ts.subjectID,
section = s.section,
className = s.name,
}).ToList();
query.ForEach(item => {
var otherItem = query1.Where(itm => itm.Id == item.Id).FirstOrDefault();
item.subjectName = otherItem?.subjectName;
item.teacherName = otherItem?.teacherName;
});
请注意,我将Id
属性添加到TeacherSubjectVM
类,以便可以对其进行合并,它应该用主题ID填充,因为它是两者之间唯一的共同点对象。
PS:使用描述性变量名称总是更好的做法,这有助于提高代码的可读性和可维护性:)