Wednesday, February 3, 2010

VB.NET Corner - fun with Linq, lambdas, and anonymous types

In my post, C# Corner - fun with 'yield' and extension methods, I discussed the common scenario of iterating over an IEnumerable<T> collection while maintaining an index.  Due to playing around with the 'yield' keyword, VB.NET was excluded from the fun.  Well, using Linq, lambda expressions, and anonymous types, we can accomplish the same results I was describing in my previous post, but now VB can participate too.  Here's the code:

Dim names = New String() {"You", "Me", "Dupree"} ' Or GetLazyLoadedNames() if you want
For Each n In names.Select(Function(x, i) New With {.Index = i, .Item = x})
   Console.WriteLine("{0}-{1}", n.Index, n.Item)
Next

This code is chock full of goodies, which doesn't make it the most readable thing in the world, but lets break it down:

The .Select() function is a simple extension method inserted into any IEnumerable via the inclusion of the System.Linq namespace.  It can take a lambda expression of the item you're interating over, as well as the index of that item.  That's the Function(x, i) part.  And finally, we have the anonymous type mimicing the data structure we discussed in the previous post consisting of the two properties - Index and Item.  VB.NET uses the New With {} syntax to define an anonymous type.  The x and i variables only have scope within the context of the Select function's lambda expression, so you can't accidentally use those variables somewhere unintended, and the anonymous type means that you don't have to have any of the supporting infrastructure classes required from our previous discussion.  All in all, not a bad way to do things (at the expense of a little readability at first).  And, just for fun, here's the C# version too:

var names = GetLazyLoadedNames();
foreach (var n in names.Select((x, i) => new {Index = i, Item = x})) {
   Console.WriteLine("{0}-{1}", n.Index, n.Item);
}

So, in these two posts, I've barely mentioned most of the feature awesomeness of the 3.5 framework just in time for the 4.0 stuff to hit the shelves.  The things I'm now able to do with the addition of Linq have made the past year of development a total joy, and I'm really interested to see what the 4.0 framework brings to the table.  Is the Entity Framework 4.0 release finally usable?