Codecamp and Linq

Posted on Posted in Uncategorized

Went to the Orlando Code Camp yesterday and was pleasantly surprised by how enjoyable and informative the sessions were. It’s always a little humbling to see all the technologies you’re not familiar with and realize you haven’t even scratched the surface of being an “expert”. 😉

The most interesting (and most crowded) seminars were definitely the Linq ones. I tried getting my toes wet with it for an my Xml updater, but just couldn’t wrap my head around it and went back to plain old DOM. After seeing LINQ to XML and LINQ to SQL sessions, it seemed a lot cooler, but I still just didn’t “get” why it was so much of a benefit. After being clued in to LinqPad, it began to click for me. LinqPad is one of the more ingenious learning tools I’ve used, especially for its simplicity.

Once I noticed that Linq works not just for Sql or Xml, but for basic collections, arrays, etc, I finally started to see how much more readable and maintainable it can make code. It can eliminate a lot of the nested foreach/if/foreach/if blocks you see scattered around business logic. Code like:

foreach (Order o in currentBatch.Orders)
if (o.ShipDate < '1/1/2008')
foreach (OrderLineItem oli in o.LineItems)
if (oli.Category == "Cookies")
{
AddFreeMilkPromotion(o);
break; //only 1 free milk per order
}

Becomes:

var query = from o in currentBatch.Orders
where o.ShipDate < '1/1/2008'
where
o.LineItems.Any(i => i.Category == "Cookies")
select o;

foreach (Order o in query)
AddFreeMilkPromotion(o);

While it doesn’t save much as far as number of lines, the bottom example just seems so much cleaner and more concise to me.

Leave a Reply

Your email address will not be published. Required fields are marked *