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 a 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 like from, were etc. and then as it makes sense in the select statement. Also put each logic operator on it’s 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.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s