Coding Style
[Blog Map] [Table of Contents] [Next Topic]
Sometimes when using the method syntax for a complicated query, you dot into method after method after method, as you can see in the example in the previous topic. These lines can get very long, and a little hard to read. One approach that I’ve used to good effect is to use a coding style where I line up the dots vertically. When coded with this style, the query is written like this:
This blog is inactive.
New blog: EricWhite.com/blog
Blog TOCvar 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 restyling of the query using a query expression looks like this:
var paragraphs =
from p in mainPartDoc.Root
.Element(w + "body")
.Descendants(w + "p")
let style = (string)p.Elements(w + "pPr")
.Elements(w + "pStyle")
.Attributes(w + "val")
.FirstOrDefault()
select new
{
ParagraphNode = p,
Style = style,
};
This can look a bit strange to some upon first glance, but sometimes I prefer this style. You just read them like queries. This is just a matter of personal preference.