baileyswalk
baileyswalk

Reputation: 1228

Dynamic Linq Query

I have been trying the following but it returns unexpected results:

    Dim xd As XDocument = _
    <?xml version="1.0" encoding="utf-8"?>
    <root>
        <element>
            <subelement id="1">
                <subsubelement id="1"/>
                <subsubelement id="3"/>
                <subsubelement id="1"/>
            </subelement>
            <subelement id="2"/>
            <subelement id="3"/>
        </element>
        <element>
            <subelement id="4"/>
            <subelement id="3"/>
            <subelement id="2">
                <subsubelement id="1"/>
                <subsubelement id="1"/>
                <subsubelement id="3"/>
            </subelement>
            <subelement id="5"/>
        </element>
    </root>

    Dim haveSubelementId As Boolean = True
    Dim haveSubSubelementId As Boolean = True

    Dim results = From q In xd...<element>
    If haveSubelementId Then
        results = From q In results.<subelement> Where q.@id = 1
    End If
    If haveSubSubelementId Then
        results = From q In results.<subsubelement> Where q.@id = 3
    End If

    results = results.Ancestors.<element>

The above result returns both 'element' nodes however it should only return the first where element/subelement@id=1/subsubelement@id=3

However if results.Ancestors. is used it returns the correct 'subelement' and if that line is not included it returns a single 'subsubelement' whih is also correct I don't understand why when mvoing to the 'element' it returns both (I realise both have a subelement with id=1 but I thought each further query would filter out the presvious results) anyone have any suggestions?

Upvotes: 1

Views: 344

Answers (1)

baileyswalk
baileyswalk

Reputation: 1228

The only way I can get it to work properly is by doing the following:

    Dim results = From q In xd...<element>
    If haveSubelementId Then
        results = From q In results.<subelement> Where q.@id = 1
    End If
    If haveSubSubelementId Then
        results = From q In results.<subsubelement> Where q.@id = 3
    End If

    For Each xe As XElement In results
        If haveSubSubelementId Then
            xe = xe.Parent.Parent
        If haveSubelementId Then
            xe = xe.Parent
        End If
        Console.WriteLine(xe.ToString)
    Next

But it looks a bit clumsy and I had hoped that it would be possible to return the correct element collection from the search query.

Upvotes: 1

Related Questions