C# Linq's ugly stepchild query syntax can be so effective

Sometimes you’re just chaining method after method with Linq or you’re in the third or fourth level nested loop. Then you take a step back and think how query syntax would do since defeating nested loops is its superpower.

Spoilers for Rectangle exercise ahead
public static int Count(string[] input)
{
     if (input.Length is 0)
         return 0;

     char[][] grid = input.Select(row => row.ToCharArray()).ToArray();

     var corners = input.Index().SelectMany(row => row.Item.Index()
                                    .Where(col => col.Item is '+')
                                    .Select(col => new Coord(row.Index, col.Index)));

     return (from topLeft in corners
             let bottomLefts = corners.Where(c => ValidVertical(topLeft, c, grid))
             where bottomLefts.Any()
             from topRight in corners.Where(c => ValidHorizontal(topLeft, c, grid))
             let bottomRights = corners.Where(c => ValidVertical(topRight, c, grid))
             where bottomRights.Any()
             from bottomLeft in bottomLefts
             from bottomRight in bottomRights.Where(c => ValidHorizontal(bottomLeft, c, grid))
             select 1).Count();
}

I don’t know anybody that prefers query syntax over method syntax but I do love it when you end up with such a readable, single block that takes care of everything you need. As you can tell even from this snippet, though, I have a method syntax first brain as well.

1 Like

Very nice!