How to do joins in LINQ on multiple fields in single join

johnc picture johnc · Dec 17, 2008 · Viewed 309.7k times · Source

I need to do a LINQ2DataSet query that does a join on more than one field (as

var result = from x in entity
join y in entity2 
       on x.field1 = y.field1 
and 
          x.field2 = y.field2

I have yet found a suitable solution (I can add the extra constraints to a where clause, but this is far from a suitable solution, or use this solution, but that assumes an equijoin).

Is it possible in LINQ to join on multiple fields in a single join?

EDIT

var result = from x in entity
             join y in entity2
             on new { x.field1, x.field2 } equals new { y.field1, y.field2 }

is the solution I referenced as assuming an equijoin above.

Further EDIT

To answer criticism that my original example was an equijoin, I do acknowledge that, My current requirement is for an equijoin and I have already employed the solution I referenced above.

I am, however, trying to understand what possibilities and best practices I have / should employ with LINQ. I am going to need to do a Date range query join with a table ID soon, and was just pre-empting that issue, It looks like I shall have to add the date range in the where clause.

Thanks, as always, for all suggestions and comments given

Answer

KristoferA picture KristoferA · Dec 17, 2008
var result = from x in entity
   join y in entity2 on new { x.field1, x.field2 } equals new { y.field1, y.field2 }