How to perform an inner join using LINQ to SQL in C#?

I’m working on a C# project and need help with LINQ to SQL. I want to do an inner join between two tables, but I’m not sure about the correct syntax.

Here’s what I’m trying to achieve:

I have a Dealer table and a DealerContact table. I want to get all the DealerContact info for each Dealer where their DealerID matches. In regular SQL, it would look something like this:

SELECT DealerContact.*
FROM Dealer 
INNER JOIN DealerContact ON Dealer.DealerID = DealerContact.DealerID

Can someone show me how to write this using LINQ to SQL? I’ve tried a few things, but they’re not working right. Any help would be great. Thanks!

yo, another way to do this is with lambda expressions. try something like:

var result = context.Dealers
.Join(context.DealerContacts,
d => d.DealerID,
c => c.DealerID,
(d, c) => c);

its pretty neat and gives you the same result. good luck with ur project!

To perform an inner join using LINQ to SQL in C#, you can utilize the join clause in combination with the equals keyword. Here’s an efficient approach:

var result = from dealer in context.Dealers
join contact in context.DealerContacts
on dealer.DealerID equals contact.DealerID
select contact;

This query will return all DealerContact records that have a matching DealerID in the Dealer table. You can then iterate through the result set to access the joined data. Remember to replace ‘context’ with your actual DataContext name.

For better performance, consider using compiled queries if you’ll be executing this join frequently.

hey there! have you tried using the join keyword in LINQ? it’s super handy for this kinda stuff. something like:

var query = from d in Dealers
join c in DealerContacts on d.DealerID equals c.DealerID
select c;

this should give you what youre after. hope it helps! let me know if you need any more info :slight_smile: