How to do a full outer join in Linq?

后端 未结 5 1947
花落未央
花落未央 2020-12-02 23:01

I\'ve inherited a database that wasn\'t designed exactly optimally, and I need to manipulate some data. Let me give a more common analogy of the kind of thing I have to do:

5条回答
  •  醉酒成梦
    2020-12-02 23:36

    Based on Shaul's answer, but with a little streamlining:

    var q =
      from id in studentIDs
      join sc in StudentClasses on id equals sc.StudentID into jsc
      join st in StudentTeachers on id equals st.StudentID into jst
      where jst.Any() ^ jsc.Any() //exclusive OR, so one must be empty
    
      //this will return the group with the student's teachers, and an empty group
      //   for the student's classes - 
      //   or group of classes, and empty group of teachers
      select new { classes = jsc, teachers = jst };
    
      //or, if you know that the non-empty group will always have only one element:
      select new { class = jsc.DefaultIfEmpty(), teacher = jst.DefaultIfEmpty() };
    

    Note that for a full outer join, this can work, too. Leave out the where clause and use the first select above, rather than the second.

提交回复
热议问题