Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple Field Join via Lambda Expression

Tags:

c#

linq

I'm trying to figure out how to introduce multiple field matches into this. Right now I'm joining based on a matching UserId to the company table. But what if I wanted to also have an AND in there such as c.SomeField = somevalue?

var companyUsers = users.Where(u => u.IsEmployee)
                        .Join(companies, 
                              u => u.UserId, c => c.UserId, 
                              (u, c) => u.UserId)
                        .ToList();
like image 878
PositiveGuy Avatar asked May 20 '26 10:05

PositiveGuy


2 Answers

If somevalue is a constant (i.e. unrelated to the user) then you should just filter companies first:

var companyUsers = users.Where(u => u.IsEmployee)
                        .Join(companies.Where(c => c.SomeField == someValue),
                              u => u.UserId, c => c.UserId, (u, c) => u.UserId)
                        .ToList();

If you need to join two fields of the user to two fields of the company, use an anonymous type as shown by SLaks.

like image 66
Jon Skeet Avatar answered May 22 '26 22:05

Jon Skeet


You need to join on anonymous types:

as.Join(bs, a => new { a.X, a.Y }, b => new { b.X, b.Y })
like image 29
SLaks Avatar answered May 22 '26 22:05

SLaks



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!