1

I am new to LINQ and wanted to write a C# LINQ query to filter nodes on a XDocument Object. How would I filter based on a date Value from within a tag, in this case the tag. I want to loop and create a new XDocument object with the filtered results by Date.

XDocument :

<?xml version="1.0" encoding="UTF-8"?>
<BMW>
<Model>
    <Desc>335</Desc>
    <ReleaseDate>6/20/2016</ReleaseDate>
    <Engine>V6</Engine>
    <BodyStyle></BodyStyle>
</Model>
<Model>
    <Desc>550</Desc>
    <ReleaseDate>7/12/2016</ReleaseDate>
    <Engine>V6</Engine>
    <BodyStyle></BodyStyle>
</Model>
<Model>
    <Desc>750</Desc>
    <ReleaseDate>8/26/2016</ReleaseDate>
    <Engine>V8</Engine>
    <BodyStyle>Executive Sedan</BodyStyle>
</Model>
</BMW>

Here's my method signature

    private XDocument FilterByDate(XDocument xDoc, DateTime filterDate)
    {

    }

My Output :

If I pass the datetime value of 08/26/2016. I should essentially get back a XDocument with the the last ModelTag.

<?xml version="1.0" encoding="UTF-8"?>
<BMW>    
<Model>
    <Desc>750</Desc>
    <ReleaseDate>8/26/2016</ReleaseDate>
    <Engine>V8</Engine>
    <BodyStyle>Executive Sedan</BodyStyle>
</Model>
</BMW>
1

1 Answer 1

2

This is how I would filter your model.

var model = xDoc.Descendants("Model")
    .Where(m => m.Element("ReleaseDate").Value == filterDate.ToString("M/d/yyyy"))
    .FirstOrDefault();

That will return an XElement. You can make your new doc with that element.

  • If you want a list of matches, then use .ToList() instead of .FirstOrDefault()

  • if you want to remove everything that's not a match, then you can negate the condition, by changing == to !=, and you add .Remove() instead of FirstOrDefault(), and of course, not assigning the "result" to a variable

Sign up to request clarification or add additional context in comments.

1 Comment

wow. Thank you for the explaining the combination of operators to tweak the results. worked for me!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.