Best ways to format LINQ queries.

Posted by Aren B on Stack Overflow See other posts from Stack Overflow or by Aren B
Published on 2010-05-27T20:07:06Z Indexed on 2010/05/27 20:11 UTC
Read the original article Hit count: 165

Filed under:
|
|
|

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.

© Stack Overflow or respective owner

Related posts about .NET

Related posts about LINQ