Archives page

Posts Tagged ‘linq’

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

Code highlighting, and the magic of LINQ

I’ve had a small block of code in my drafts folder for quite some time now, just looking for an excuse to publish it.  I’ve been using LINQ a lot in the past 6 months, and it’s one of the recent additions to the language that’s made me think twice before using PHP or Perl for my own projects (despite the existence of PHPLinq).

HIM: LINQ’s like pringles
ME: only makes sense after drugs?
HIM: once you pop you can’t stop

But I didn’t really want to write a full post on LINQ.  It seemed dull.  It’d been done before.  It’s old news.

So I picked up the WP-SynHighlight extension for WordPress.  Which gives some rather cool code-highlighting through GeSHi.

So here’s some highlighted stylised C# LINQ demonstrating how simple it is to combine LINQ to SQL with LINQ to XML data sources.
[codesyntax lang=”csharp”]var answers = (from a in poll.Descendants(“AnswerSet”).Descendants(“Answer”)
join aCount in dbVotes
on a.Attribute(“id”).Value equals aCount.AnswerId.ToString() into aJoined
from o in aJoined.DefaultIfEmpty()
select new {
id = a.Attribute(“id”).Value,
percentage = ((o == null ? 0 : o.VotesCount) / dbVotes.Sum(b => b.VotesCount.GetValueOrDefault()) * 100),
count = o == null ? 0 : o.VotesCount, text = a.Value
});
[/codesyntax]

Now if only Microsoft would release LINQ to XSD out of preview.