Formatting LINQ Statements

Language-Integrated Query (LINQ) was introduced in Visual Studio 2008/ .NET 3.5 and was actually one of my favorite features. It makes writing queries so much easier, especially for XML and object collections. Even though Visual Studio 2013 auto-formats the queries better, there is even an even better way to make them more readable.

Here is how Visual Studio 2013 auto-formats a LINQ query:

var query = from p in persons
            where p.Age > 30 && p.HomeAddress.City == "Los
                                                      Angeles"
            select new
              {
                  Name = string.Format("{0} {1}",
                             p.NameFirst, p.NameFirst),
                    SSN = p.SSN
              };

After working with LINQ ever since it came out, I have come up with the following formatting that I like better because it’s easier to read:

var query = from
               p in persons
            where
                p.Age > 30 &&
                p.HomeAddress.City == "Los Angeles"
            select new
                {
                    Name = string.Format("{0} {1}",
                               p.NameFirst, p.NameFirst),
                    SSN = p.SSN
                };

Indent on each LINQ keyword and then as it makes sense in the select statement. Also, put each logic operator on its own line. This is a short LINQ statement but when it gets to be a very large one this formatting makes it much easier to read.

Pick up any books by David McCarter by going to Amazon.com: http://bit.ly/RockYourCodeBooks

One-Time
Monthly
Yearly

Make a one-time donation

Make a monthly donation

Make a yearly donation

Choose an amount

$5.00
$15.00
$100.00
$5.00
$15.00
$100.00
$5.00
$15.00
$100.00

Or enter a custom amount

$

Your contribution is appreciated.

Your contribution is appreciated.

Your contribution is appreciated.

DonateDonate monthlyDonate yearly

If you liked this article, please buy David a cup of Coffee by going here: https://www.buymeacoffee.com/dotnetdave

© The information in this article is copywritten and cannot be preproduced in any way without express permission from David McCarter.


Discover more from dotNetTips.com

Subscribe to get the latest posts sent to your email.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.