Mark Needham

Thoughts on Software Development

Getting a strongly typed collection using LINQ to Xml

without comments

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) of InnerNode values.

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:

1
2
3
4
5
6
7
8
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:

1
2
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.

Written by Mark Needham

August 30th, 2008 at 3:03 am

Posted in .NET

Tagged with , ,

Leave a Reply