Getting a strongly typed collection using LINQ to Xml
I mentioned earlier that I have been playing around with LINQ to Xml for parsing a Visual Studio csproj file.
While having namespace issues I decided to try and parse a simpler Xml file to try and work out what I was doing wrong.
Given this fragment of Xml:
<Node>
<InnerNode>mark</InnerNode>
<InnerNode>needham</InnerNode>
</Node>
I wanted to get a collection(IEnumerable
Unfortunately my over enthusiasm to use anonymous types meant that I caused myself more problems than I needed to. This was my original (failed) effort at doing so:
var innerNodes = from node in projectFile.Descendants("Node").Elements()
select new {InnerNode = node.Value};
IList<string> innerNodesAsCollection = new List<string>();
foreach (var innerNode in innerNodes)
{
innerNodesAsCollection.Add(innerNode.InnerNode);
}
A very round about way of solving the problem I’m sure you’ll agree. I was sure this should be easy to do but I was making it very complicated indeed. A bit more googling revealed that I could put items straight into the collection from the LINQ query by not using anonymous types:
IEnumerable<string> innerNodes = from node in projectFile.Descendants("Node").Elements()
select node.Value;
Much less code, much simpler, and a lesson in the art of not over complicating things.
About the author
I'm currently working on short form content at ClickHouse. I publish short 5 minute videos showing how to solve data problems on YouTube @LearnDataWithMark. I previously worked on graph analytics at Neo4j, where I also co-authored the O'Reilly Graph Algorithms Book with Amy Hodler.