PositiveGuy
PositiveGuy

Reputation: 47733

Multiple Field Join via Lambda Expression

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();

Upvotes: 3

Views: 7250

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1499770

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.

Upvotes: 4

SLaks
SLaks

Reputation: 887195

You need to join on anonymous types:

as.Join(bs, a => new { a.X, a.Y }, b => new { b.X, b.Y })

Upvotes: 3

Related Questions