如何在 Linq 中进行完整的外部联接?

How to do a full outer join in Linq?(如何在 Linq 中进行完整的外部联接?)
本文介绍了如何在 Linq 中进行完整的外部联接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我继承了一个没有完全优化设计的数据库,我需要处理一些数据.让我对我必须做的事情做一个更常见的类比:

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:

假设我们有一个 Student 表,一个 StudentClass 表记录他参加的所有课程,以及一个 StudentTeacher 表存储所有教过这个学生的老师.是的,我知道这是一个愚蠢的设计,将老师存储在 Class 桌子上会更有意义 - 但这就是我们正在使用的.

Let's say we have a Student table, a StudentClass table keeping record of all the classes he attended, and a StudentTeacher table that stores all the teachers who taught this student. Yes, I know it's a dumb design and it would make more sense to store the teacher on the Class table - but that's what we're working with.

我现在想清理数据,我想找到一个学生有老师没有课的地方,或者有课没有老师的地方.SQL因此:

I now want to clean up the data, and I want to find all the places where a student has a teacher but no classes, or a class but no teachers. SQL thus:

select *
from StudentClass sc
full outer join StudentTeacher st on st.StudentID = sc.StudentID
where st.id is null or sc.id is null

你如何在 Linq 中做到这一点?

How do you do that in Linq?

推荐答案

我想我在这里有了答案,虽然没有我希望的那么优雅,但它应该可以解决问题:

I think I have the answer here, which is not as elegant as I'd hoped, but it should do the trick:

var studentIDs = StudentClasses.Select(sc => sc.StudentID)
  .Union(StudentTeachers.Select(st => st.StudentID);
  //.Distinct(); -- Distinct not necessary after Union
var q =
  from id in studentIDs
  join sc in StudentClasses on id equals sc.StudentID into jsc
  from sc in jsc.DefaultIfEmpty()
  join st in StudentTeachers on id equals st.StudentID into jst
  from st in jst.DefaultIfEmpty()
  where st == null ^ sc == null
  select new { sc, st };

您可能可以将这两个语句合二为一,但我认为您会牺牲代码的清晰度.

You could probably squeeze these two statements into one, but I think you'd sacrifice code clarity.

这篇关于如何在 Linq 中进行完整的外部联接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

LINQ to SQL query using quot;NOT INquot;(使用“NOT IN的 LINQ to SQL 查询)
LINQ to SQL Web Application Best Practices(LINQ to SQL Web 应用程序最佳实践)
How do I group data in an ASP.NET MVC View?(如何在 ASP.NET MVC 视图中对数据进行分组?)
how to update the multiple rows at a time using linq to sql?(如何使用 linq to sql 一次更新多行?)
how to recognize similar words with difference in spelling(如何识别拼写不同的相似词)
C# Linq to SQL: How to express quot;CONVERT([...] AS INT)quot;?(C# Linq to SQL:如何表达“CONVERT([...] AS INT)?)