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
Make a one-time donation
Make a monthly donation
Make a yearly donation
Choose an amount
Or enter a custom amount
Your contribution is appreciated.
Your contribution is appreciated.
Your contribution is appreciated.
DonateDonate monthlyDonate yearlyIf 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.
