Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ: How to do JOIN using the linq extension method style on multiple fields?

Tags:

join

linq

field

In the Join below, I'd like to use multiple fields to do the join rather than just one field.

var join = group.Join(procSums, g => g.DeptID, ps => ps.key.deptID, (g, ps)...

All examples Ive found use the query style to do this and I can't translate it.

Thanks!

like image 580
user259286 Avatar asked Apr 27 '11 17:04

user259286


People also ask

Can we use joins in Linq?

In LINQ, an inner join is used to serve a result which contains only those elements from the first data source that appears only one time in the second data source. And if an element of the first data source does not have matching elements, then it will not appear in the result data set.

How does join work in Linq?

In a LINQ query expression, join operations are performed on object collections. Object collections cannot be "joined" in exactly the same way as two relational tables. In LINQ, explicit join clauses are only required when two source sequences are not tied by any relationship.


2 Answers

You just have to Join based on new anonymous objects:

// ClasID is a placeholder, it could be any property you'd like
var join = group.Join(procSums,
                      g => new { g.DeptID, g.UnitLoc, g.Proc },
                      ps => new 
                            { 
                              DeptID = ps.key.deptID, 
                              UnitLoc = ps.key.unitLoc,
                              Proc = ps.key.procName 
                            },
                      (g, ps) => new { g, ps });
like image 125
Justin Niessner Avatar answered Oct 18 '22 23:10

Justin Niessner


You need to pass lambda expressions that create anonymous types with the fields.
For example:

group.Join(procSums, g => new { g.DeptID, g.OtherField }, ps => new { ps.key.deptID, ps.key.OtherField }, ...)

The anonymous types must match exactly.

like image 1
SLaks Avatar answered Oct 19 '22 00:10

SLaks