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);

:-)