views:

13

answers:

1

What's the most elegant way of going from this:

<?xml version="1.0" encoding="UTF-8"?>
<foo>
<bar baz="wii" date="2009-01-01">
    <baz value="0" />
    <baz value="1" />
</bar>
<bar baz="wii" date="2009-01-02">
    <baz value="0" />
    <baz value="1" />
</bar>
<bar baz="xbox" date="2009-01-01">
    <baz value="0" />
    <baz value="1" />
</bar>
<bar baz="xbox" date="2009-01-02">
    <baz value="0" />
    <baz value="1" />
</bar>
</foo>

to this:

<foo>
<bar baz="wii" date="2009-01-02">
    <baz value="0" />
    <baz value="1" />
</bar>
<bar baz="xbox" date="2009-01-02">
    <baz value="0" />
    <baz value="1" />
</bar>
</foo>

Ideally, this is a function taking a "date" parameter. The obvious creation of and looping through to add each from an expression that returns IEnumerable<XElement> seems clunky so there's probably a nicer way.

A: 

I think the obvious way you describe is actually the best. A pure LINQ approach could look like

private static XDocument FilterByDate(XDocument doc, DateTime dateTime)
{
    return doc.Root.Elements()
                    .Where(xe => DateTime.Parse(xe.Attribute("date").Value) == dateTime)
                    .Aggregate(new XDocument(new XElement("foo")),
                                            (xd, xe) => { xd.Root.Add(xe); return xd; });
}

But I think the Aggregate part is not very efficient.

Jens