Inner join with multiple parameters with LINQ

Today at work in ran into a problem where I needed to do an inner join of two tables, but with multiple criteriums.
At first it wasn’t quite obvious how it should be done, but the solution was quite simple actually:

Making a simple join with one criteria is easy:

1
2
3
4
5
6
var Result = from t1 in db.Table1  
join t2 in db.Table2 on t1.Value1 equals t2.Value1
select new {
Value1 = t1.FieldFromTable1,
Value2 = t2.FieldFromTable2
}

Making it with multiple criteriums is almost as easy

You just need to create anonymous objects.

1
2
3
4
5
6
7
var Result = from t1 in db.Table1  
join t2 in db.Table2 on new { criteria1 = t1.Value1, criteria2 = t1.Value2 }
equals new { criteria1 = t2.Value1, criteria2 = t2.Value2 }
select new {
Value1 = t1.FieldFromTable1,
Value2 = t2.FieldFromTable2
}

Comments: