Best ways to format LINQ queries

Aren picture Aren · May 27, 2010 · Viewed 12.6k times · Source

Before you ignore / vote-to-close this question, I consider this a valid question to ask because code clarity is an important topic of discussion, it's essential to writing maintainable code and I would greatly appreciate answers from those who have come across this before.

I've recently run into this problem, LINQ queries can get pretty nasty real quick because of the large amount of nesting.

Below are some examples of the differences in formatting that I've come up with (for the same relatively non-complex query)

No Formatting

var allInventory = system.InventorySources.Select(src => new { Inventory = src.Value.GetInventory(product.OriginalProductId, true), Region = src.Value.Region }).GroupBy(i => i.Region, i => i.Inventory);

Elevated Formatting

var allInventory = system.InventorySources
    .Select(src => 
        new { 
            Inventory = src.Value.GetInventory(product.OriginalProductId, true), 
            Region = src.Value.Region })
                .GroupBy(
                    i => i.Region, 
                    i => i.Inventory);

Block Formatting

var allInventory = system.InventorySources
    .Select(
        src => new 
        { 
            Inventory = src.Value.GetInventory(product.OriginalProductId, true), 
            Region = src.Value.Region 
        })
        .GroupBy(
            i => i.Region, 
            i => i.Inventory
        );

List Formatting

var allInventory = system.InventorySources
    .Select(src => new { Inventory = src.Value.GetInventory(product.OriginalProductId, true), Region = src.Value.Region })
    .GroupBy(i => i.Region, i => i.Inventory);

I want to come up with a standard for linq formatting so that it maximizes readability & understanding and looks clean and professional. So far I can't decide so I turn the question to the professionals here.

Answer

Amy B picture Amy B · May 27, 2010

My Formatting:

var allInventory = system.InventorySources
  .Select(src => new
  {
    Inventory = src.Value.GetInventory(product.OriginalProductId, true),
    Region = src.Value.Region
  })
  .GroupBy(
    i => i.Region,
    i => i.Inventory
  );

Notes:

  • Opening parens on methods are never worthy of a new line.
  • Closing parens match the indenting of the line that contains the opening paren.
  • The src => new stays on the same line as Select, because it's just not worthy of a new line.
  • The anonymous type always gets block treatment, just like if it was used outside of a query (but the closing paren is not worthy of a new line).
  • The two parameter GroupBy overload is not typically called. Although it could easy fit on a single line, use an extra line to make it clear that something unusual is happening.