Blog - Title

Formatting LINQ Code

Formatting LINQ Code

  • Comments 1

Over time, I’ve adjusted my code formatting style – changing the white space that I insert, or where I place the parentheses.  In this post, I detail some aspects of my current code formatting approach, focusing only on formatting LINQ queries that are written in the ‘method syntax’, not using LINQ query expressions (from --- select ---).

This blog is inactive.
New blog: EricWhite.com/blog

Blog TOC
Often in the past, I have leaned towards formatting code with an emphasis on reducing line code.  I like to see more of my code in a given window, not less.  However, when formatting queries, there is one situation where I have tended towards a coding style that increases line count.  Of course, this doesn’t increase
cyclomatic complexity.

First of all, formatting for a short lambda expression is written, of course, like this:

var t2 = t1.Select(l => l.ToUpper());

 

When newing up a nominal or anonymous type in a select statement, I place the arguments to the lambda expression on the same line as the Select call, and start the instantiation of the anonymous type on the next line, indented:

var paragraphs =

    mainPartDoc.Root

       .Element(w + "body")

       .Descendants(w + "p")

    .Select(p =>

        new

        {

            ParagraphNode = p,

            Style = (string)p

                .Elements(w + "pPr")

                .Elements(w + "pStyle")

                .Attributes(w + "val")

                .FirstOrDefault()

        }

    );

 

The above example also shows my already documented approach to lining up the “dots” for a longer query.  In some earlier examples, I lined up the dots like so:

Style = (string)p.Elements(w + "pPr")

                 .Elements(w + "pStyle")

                 .Attributes(w + "val")

                 .FirstOrDefault()

 

However, I find that sometimes this indents the ‘lined up method calls’ too far, so I now indent just four spaces:

Style = (string)p

    .Elements(w + "pPr")

    .Elements(w + "pStyle")

    .Attributes(w + "val")

    .FirstOrDefault()

 

When I have ‘statement lambda expressions’, I have a new way that I write it, where I place the opening parenthesis of the Select statement on its own line, place the argument(s) to the lambda expression on its own line, and the opening brace on its own line:

XElement xmlDoc = new XElement("Root",

    File.ReadAllLines("TextFile.txt")

        .Select

        (

            line =>

            {

                var split = line.CsvSplit();

                return new XElement("Quote",

                    new XElement("Person", split[0]),

                    new XElement("Text", split[1])

                );

            }

        )

);

 

The reason I like this – it more closely parallels declaration of methods in a class.  I can clearly see the arguments to the lambda expression, and the body of the lambda.  I normally like to have ‘lined-up’ braces, and in this case, the parentheses of the Select method call are at their own level of indentation, so I also like to line them up.

I’ve seen another coding style that looks like this:

XElement xmlDoc = new XElement("Root",

    File.ReadAllLines("TextFile.txt")

        .Select(line => {

                var split = line.CsvSplit();

                return new XElement("Quote",

                    new XElement("Person", split[0]),

                    new XElement("Text", split[1])

                );

            }));

 

This certainly conserves vertical space, but I find it inconvenient when making sure that my braces and parentheses are properly placed.

But this is all just a matter of style.  I’d really like to hear how you do it.  I invite you to leave comments on this post showing how you format code.  I know that pasting comments in this blog doesn’t allow you to format code very nicely – if you shoot me an email, I’d be happy to reformat your comment so that it shows your intent in formatting.

Leave a Comment
  • Please add 1 and 3 and type the answer here:
  • Post
  • I generally try to stick with the rules that VS code formatter uses (if only because I don't want my neat code to be broken by Ctrl+K, Ctrl+D). For chained method calls, when wrapping them on several lines, this means indenting the second line and those afterwards by a single tab (and not line up the dots).

    I always leave the opening parenthesis on the same line as the method it applies to in method calls, because this is consistent with method declarations. I.e., I do:

    .Select(

     ...);

    rather than:

    .Select(

     ...

    )

    because when I declare methods, I also do:

    void Foo(

     int arg1,

     int arg2);

    On the other hand, for curly braces, if they aren't both on the same line, I put each on its own separate line with nothing else there; so the lambda looks like this:

    item =>

    {

      ...

    }

    and not:

    item => {

      ...

    }

    This one is actually sorta enforced by VS - if you write the second code snippet, you will see how VS will reformat it using the first style as you type the closing curly brace. It also does that for arrays and object initializers, by the way.

    On the whole, I find that if I use a raw method-call LINQ query, I try to fit it on a single line, and if that fails, I start to introduce temporary variables with descriptive names. Otherwise, I switch over to language-integrated query syntax which is much easier to arrange over several lines (and VS does a good job at doing it automatically, too) - but this is not an option for those long LINQ to XML queries, of course.

Page 1 of 1 (1 items)