How to do a full outer join in 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 中进行完整的外部联接?
基础教程推荐
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
