Monday, December 10, 2007

Linq + Anonymous Types = bliss

If you've ever been faced with the task of reading in a list of object properties from XML and instantiating objects with the node text, you know that while it is relatively straightforward on the surface, it still can be a lot of hassle to create the DOM object, work up the XPath to get what you want, create a strongly-typed object to hold the properties you are pulling, and test and convert the node inner text and stuff it into the object.

I have been following along Scott Guthrie's description/tutorial of the new ASP.NET MVC Framework and ran across a little tidbit that made the job of using XML in my application a whole lot easier: using anonymous types and the results from a Linq query to populate them. Here's an example:


XDocument buildFile = XDocument.Load(args[0]);

var builds = from file in buildFile.Descendants("file")
select new
{
SourcePath = file.Element("sourcePath").Value,
TargetPath = file.Element("targetPath").Value,
ReplaceToken = file.Element("replaceToken").Value,
ReplaceWith = file.Element("replaceWith").Value
};

foreach (var file in builds)
{
ReplaceInFile.Replacer replacer = new Replacer(
file.SourcePath,
file.TargetPath,
file.ReplaceToken,
file.ReplaceWith);

string contents = replacer.Replace();

Utilities.SaveFile(file.TargetPath, contents);
}


The anonymous type comes in really handy here because I only need it for a very limited purpose and will not need it anywhere else. Previously I would have created a new class to hold the properties, but now I can do it on the fly.

Maybe calling it blissful is a bit much, but it definitely is an improvement over the old way of doing things.

No comments: