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.

Code block    
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

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

Tags: , , , , , ,

Leave a Reply?