Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine 2 LINQ queries

Tags:

c#

linq

I am trying to join 2 LINQ queries. But I am not getting result according to my desire.

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

Class name and section should be in the same row of subject name and teacher name:

like image 352
Umair Avatar asked Jul 09 '26 00:07

Umair


1 Answers

Simply join all the tables you want to join in a single step:

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

I think that's what you are trying to do but your inconsistent variable naming and reuse of variable names makes it really hard to read.

like image 133
Ian Mercer Avatar answered Jul 11 '26 13:07

Ian Mercer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!