DEV Community

Cover image for Why I Write My LINQ Queries Tall, Not Wide
Milan Jovanović
Milan Jovanović

Posted on • Originally published at milanjovanovic.tech on

Why I Write My LINQ Queries Tall, Not Wide

Wishing You a Warm Welcome

First, I want to welcome you to the first edition of Milan's .NET Weekly newsletter.

I hope that this newsletter can become a positive force in the .NET community. To bring many of us together so that we can all continue learning and improving.

With that out of the way, let's get into .NET!

The Problem With Wide LINQ

Let's consider the following LINQ expression from a code style perspective.

I call this a wide LINQ expression, because it stretches horizontally across the entire screen.

dbContext.Animals.Where(animal => animal.HasBigEars)
    .OrderBy(animal => animal.IsDangerous).Select(
        animal => (animal.Id, animal.Name)).ToList();
Enter fullscreen mode Exit fullscreen mode
  • It is difficult to read.
  • It is difficult to reason about.
  • It is difficult to extend or maintain.

To improve this, I created a simple rule that you can follow:

When writing LINQ, try to go tall, not wide.

How to Write Tall LINQ

So how do we write tall LINQ expressions?

I'm going to rewrite the previous expression, to improve it.

Try to follow the one dot per line rule:

dbContext
    .Animals
    .Where(animal => animal.HasBigEars)
    .OrderBy(animal => animal.IsDangerous)
    .Select(animal => (animal.Id, animal.Name))
    .ToList();
Enter fullscreen mode Exit fullscreen mode

Is the new version easier to read? Yes , very much so.

It is easier to understand what each expression does, and how it feeds into the next one in the chain.

If you are working in a team, try to propose this as a coding standard (if it isn't one already).

You will see that over time this will make a noticeable difference.


P.S. Whenever you're ready, there are 2 ways I can help you:

  1. Pragmatic Clean Architecture: This comprehensive course will teach you the system I use to ship production-ready applications using Clean Architecture. Learn how to apply the best practices of modern software architecture. Join 950+ students here.

  2. Patreon Community: Think like a senior software engineer with access to the source code I use in my YouTube videos and exclusive discounts for my courses. Join 820+ engineers here.

Top comments (2)

Collapse
 
shaijut profile image
Shaiju T

Welcome Milan to Dev.to 😊 , Hope your content sky rockets here for .NET community. Kindly add dotnet tag also to reach more readers.

dev.to/t/dotnet/top/week

Collapse
 
milanjovanovictech profile image
Milan Jovanović

That's a great suggestion, Shaiju! Much appreciated :)