Tuesday, 20 May 2008

XLinq in C#

I have been converting some rather inelegant bits of C# code (stuff I had written, no reflection on anyone else) from the DotNet 2.0 XPathNavigable way of doing things to the DotNet 3.0 Linq way of doing things.

Using XLinq (Linq on XML) is fun. It's a shiny new hammer that you can use for banging in all sorts of nails, but you can get a bit carried away.

In my case, I have been extracting the externalNames (think, fully qualified names) of some XSOL variables and stuffing them in a Collection called variables. MSDN has trivial examples that are more or less like this
IEnumerable externalNames =
from externalName in root.Descendants("externalName")
select (string)externalName;

foreach (string name in externalNames)
{
  variables.Add(name);
}

That all seems simple enough: extract the contents of the descendant elements.

Of course, it can be collapsed to make things a little more elegant without making them more obscure:

foreach (string name in
from externalName in root.Descendants("externalName") select (string)externalName)
{
  variables.Add(name);
}

But then I get to thinking, why not do it all in one go? The result of all that Linq stuff is an IEnumerable. I can't implicitly convert it to a Collection but there is an overload for the constructor for Collection<> that will do the trick:

variables = new Collection(
(from externalName in root.Descendants("externalName") select (string)externalName)
.ToList());


So there you go. You can do it using the new shiny hammer but things are starting to look more complex than is necessary. Thinking about it some more, it really is sufficient to skip all that Linq and say
foreach (XElement externalName in root.Descendants("externalName"))
{
  variables.Add(externalName.Value);
}


This is not to say that XLinq is not a good thing. Clearly it would be wonderful for more complex queries.

No comments: