C# Joins with Linq and Lambdas
I’m always forgetting the syntax for lambda joins in C#, because I never use them enough and get bored looking for reminders enough that I just revert back my old ways and use the query expression instead. So rather than find a good tutorial and bookmark it, I’ll post it here instead. By the time it falls off the front page, I’ll just about have remembered how to do it without needing this anyway 🙂
Query Syntax
[codesyntax lang=”csharp”]var products = from audio in DbContext.DataContext.ProductAudios
join product in DbContext.DataContext.ProductAudios on audio.ProductId equals product.ProductId
select new { Product = product, Audio = audio };
[/codesyntax]
Lambda Syntax
[codesyntax lang=”csharp”]var products = DbContext.DataContext.ProductAudios.Join(
DbContext.DataContext.Products,
audio => audio.ProductId,
product => product.ProductId,
(audio, product) => new { Product = product, Audio = audio });
[/codesyntax]
It might look like more code because of my formatting, but I find the lambda syntax much convenient when chaining queries together with other where’s and groupby’s, especially when that might be split across different methods. It also isolates your join nicely, whereas I find the query syntax will start to get particularly unreadable with more complex queries.
Last but not least, another piece of linq-join-related syntax I’m finding myself always having to look up a lot is for left outer joins. Fortunately I always end up at MSDN for that one, so I’ll just link to it here:
How to: Perform Left Outer Joins