Visual Basic vs C# LINQ syntax
LINQ has two syntaxes – Lamda syntax and Comprehension syntax. Each has their uses and you can happily mix them.
Lamda syntax is stuff like:
var longWords = words.Where( w => w.length > 10);
Dim longWords = words.Where(Function(w) w.length > 10)
Where as Comprehension syntax is much more similar to SQL and hence it is often referred to as Query syntax:
var longwords = from w in words where w.length > 10;
Dim longwords = From w In words Where w.length > 10
Interestingly the VB and C# team each did their own work on the Comprehension syntax with different final results. The VB team did all that lovely XML literals stuff but they also did something slightly less obvious. The following VB code using Comprehension syntax to skip the first 10 Orders and then return just the next 5.
Dim q = From o In db.Orders Select o.OrderID Skip 10 Take 5
But C# has no equivalent Comprehension syntax – hence you need to use Lamda syntax.
var q = from o in db.Orders select o.OrderID;
q = q.Skip(10).Take(5);
Although I bet many of you want to write:
var q = ((from o in db.Orders select o.OrderID).Skip(10)).Take(5);
:-)
Comments
Anonymous
August 05, 2008
> var q = ((from o in db.Orders select o.OrderID).Skip(10)).Take(5); That's an extra unnecessary pair of parentheses. Why not just: var q = (from o in db.Orders select o.OrderID).Skip(10).Take(5); Well, unless one is a closet Lisp lover?Anonymous
August 05, 2008
It's too bad the language teams couldn't settle on common syntax and case for the LINQ keywords. It make it tough for developers who need to switch between VB and C#. BTW, when you're spinning while converting VB LINQ to C# LINQ, the tool here can save you hours: http://vbconversions.net/ . KenAnonymous
August 05, 2008
"Closet LISP lover" :-) Well - most of my Unix development was done using a highly customised GNU EMACS - customised using LISP. So yep - I got to see plenty of brackets :-) And yep - i added some extra ones without thinking ...Anonymous
August 05, 2008
VB/C# LINQ keywords mostly match where they are present in both languages (though why we couldn't have "order by" with C# rather than "orderby" is anyone's guess... especially when C# also uses "group by"). But missing "skip" and "take" are surely annoying. Oh, and I also want my SelectMany in both languages. So far, it seems that Oxygene - a 3rd party language! - has got the most powerful LINQ syntax; shame on both C# and VB teams! ;)