问题描述
我正在尝试在LINQ中实现一个查询,该查询在ON子句中使用具有多个条件的左外部联接.
I'm trying to implement a query in LINQ that uses a left outer join with multiple conditions in the ON clause.
我将使用以下两个表的示例: Project (ProjectID,ProjectName)和 Task (TaskID,ProjectID,TaskName,已完成).我想查看所有项目的完整列表以及它们各自的任务,但只能看到已完成的那些任务.
I'll use the example of the following two tables Project (ProjectID, ProjectName) and Task (TaskID, ProjectID, TaskName, Completed). I want to see the full list of all projects with their respective tasks, but only those tasks that are completed.
我不能为Completed == true
使用过滤器,因为这将过滤掉所有未完成任务的项目.相反,我想将Completed == true
添加到联接的ON子句中,以便显示完整的项目列表,但仅显示已完成的任务.没有完成任务的项目将显示一行,且Task的值为空.
I cannot use a filter for Completed == true
because that will filter out any projects that do not have completed tasks. Instead I want to add Completed == true
to the ON clause of the join so that the full list of projects will be shown, but only completed tasks will be shown. Projects with no completed tasks will show a single row with a null value for Task.
这是查询的基础.
from t1 in Projects
join t2 in Tasks
on new { t1.ProjectID} equals new { t2.ProjectID } into j1
from j2 in j1.DefaultIfEmpty()
select new { t1.ProjectName, t2.TaskName }
如何在on子句中添加&& t2.Completed == true
?
How do I add && t2.Completed == true
to the on clause?
我似乎找不到有关如何执行此操作的任何LINQ文档.
I can't seem to find any LINQ documentation on how to do this.
推荐答案
您只需要在匿名属性上使用相同的名称
You just need to name the anonymous property the same on both sides
on new { t1.ProjectID, SecondProperty = true } equals
new { t2.ProjectID, SecondProperty = t2.Completed } into j1
根据@svick的评论,这是另一个可能更有意义的实现:
Based on the comments of @svick, here is another implementation that might make more sense:
from t1 in Projects
from t2 in Tasks.Where(x => t1.ProjectID == x.ProjectID && x.Completed == true)
.DefaultIfEmpty()
select new { t1.ProjectName, t2.TaskName }
这篇关于LINQ在On子句中具有多个条件的联接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!