Reputation: 28306
In the following LINQ statement, I'm trying to select people but only if their Id appears in another table (a join table). What am I missing?
In this example, I have a People table and a Contractors table. The Person's contactId may appear in the Contractors table. I want to grab the contactId of People that appear in the Contractors table.
var allPeople = People.Where(x => x.Contractors
.Where(m=> m.ContactID == x.ContactID)
.Select(x => x.ContactID));
Upvotes: 0
Views: 553
Reputation: 8926
How about regular LINQ JOIN statement:
var peopleWithContact = People.Join(
Contractors,
p => p.ContactId, // the field to join by from People table
c => c.ContactId, // the field to join by from Contractors table
(p, c) => p.ContactId); // the result if match; could be just p.
Upvotes: 1
Reputation: 24360
The Where
function must return a boolean expression. If I understand your question correctly, you only want people from the peoples table that are in the contractors table as well. Then we can ask just that: Give me a person if any contractor has that ID:
var allPeople = People.Where(x => x.Contractors
.Any(m => m.ContactID == x.ContactID));
Upvotes: 0