I'm parsing some XML and need to do one thing if there are a group of XML elements with the same name and another thing if just one element with a given name.
Here my first attempt, yuck!
XElement on = null;
foreach (XElement element in elements.OrderBy(x => x.Name.LocalName))
{
var current = element;
if (elements.Count(x => current.Name.LocalName.Equals(x.Name.LocalName)) > 1)
{
if (on == null || !current.Name.LocalName.Equals(on.Name.LocalName))
{
yield return new JProperty(current.Name.LocalName,
new JArray(
elements.Where(x => current.Name.LocalName.Equals(x.Name.LocalName)).Select(
x => new JValue(x.Value))));
on = current;
}
}
else
{
yield return FromElement(element);
}
}
That's really bad, Linq is probably making the code worse. After some refactoring...
foreach (var group in from e in elements group e by e.Name.LocalName)
if (group.Count() > 1)
yield return new JProperty(group.First().Name.LocalName,
new JArray(from x in @group select new JValue(x.Value)));
else
yield return FromElement(group.First());
The code here is easier to read shorter and clearer. Much better.