C# – LINQ syntax vs. LINQ extension methods

October 24, 2011 in Programming

The LINQ syntax in C# is purely syntactic sugar for the LINQ extension methods in the System.Linq namespace.  Now, syntactic sugar doesn’t bother me so much if it seems to provide a better coding experience while still being readable.  However, the LINQ syntax in C#, however, has always reeked of “excessive crap that I have trouble formatting and reading.”

In short: I don’t want SQL in my C#, I want C# in my C#!

Anyway, here are two examples of the same LINQ query.  The first example uses the LINQ syntax, the other one just calls extension methods.

C# LINQ Syntax:

from u in Users
where u.Type == UserTypes.Admin
orderby u.Name
select new { Name = u.Name, Email = u.Email }

Regular C# syntax

Users
    .Where(u => u.Type == UserTypes.Admin)
    .OrderBy(u => u.Name)
    .Select(u => new { Name = u.Name, Email = u.Email });

Now, I don’t know about the rest of the C# world, but the LINQ syntax seems very un-C#-like.  Also, for long queries, I am not really sure a of proper way to format the LINQ code.  Also, I can never remember the subtleties of the LINQ syntax (admittedly, this is from disuse).

The second form seems more natural to me.  Each line has it’s own defined lambda expression.  I could use different lamda expression arguments for each individual call.  I can ALSO mix-and-match some of the calls.  Like:

Users
    .Where(u => u.Type == UserTypes.Admin)
    .Select(u => new { Name = u.Name, Email = u.Email })
    .OrderBy(u => u.Name);

The output of this would be the same.   Also, using the regular C# syntax and Intellisense allows me to explore the LINQ extension methods and find alternate ways of tackling a problem with LINQ that the LINQ syntax does not allow me to do.

There is one thing that the LINQ syntax does make easier:  Joins.  The extension method syntax can get a bit messy for join operations, especially when you get into outer-joins.

Your preference? Am I missing something by using the LINQ syntax that would really make using it easier?