Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ Join with Multiple Conditions in On Clause

Tags:

join

linq

I'm trying to implement a query in LINQ that uses a left outer join with multiple conditions in the ON clause.

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.

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.

Here's the foundation of the query.

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 } 

How do I add && t2.Completed == true to the on clause?

I can't seem to find any LINQ documentation on how to do this.

like image 705
Kuyenda Avatar asked Oct 05 '11 16:10

Kuyenda


People also ask

Can we use multiple conditions for on clause?

You can specify multiple conditions in a single WHERE clause to, say, retrieve rows based on the values in multiple columns. You can use the AND and OR operators to combine two or more conditions into a compound condition. AND, OR, and a third operator, NOT, are logical operators.


1 Answers

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 

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 } 
like image 82
Aducci Avatar answered Sep 20 '22 15:09

Aducci