William Smith
William Smith

Reputation: 1959

LINQ to XML, is there a better way to determine if an element exists in a list?

I am working with LINQ to XML in VB (although answers in C# are great, too). First off- my code works, so this is not critical. However, I can't help but think that what I'm doing with conditional logic should already be doable using the LINQ query itself.

Here's what I've got:

        'Get the Description elements in the ResultData section where the value is "Op Code"
        Dim opCodes As List(Of XElement) = (From c In xdoc.Descendants("ResultData").Descendants("Description")
                 Where c.Value = "Op Code"
                 Select c).ToList()

        If opCodes.Count > 0 Then
            'Get the sibling XElement of the first "Description" XElement (there should be only one) by using the parent
            sOperator = Convert.ToString(((From c In opCodes
                     Select c).FirstOrDefault().Parent).<Value>.Value)
        Else
            sOperator = "Not Available"
        End If

Please don't be too critical of my method of locating the sibling nodes- the XML files are produced by a third-party testing device and this is the only generic way to get the values I need. What I'm really looking for here is a better way to handle the If block.

Any thoughts offered on this will be greatly appreciated.

Upvotes: 1

Views: 766

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1502086

It sounds like you want (C#):

string operator = xdoc.Descendants("ResultData")
                      .Descendants("Description")
                      .Where(x => x.Value == "Op Code")
                      .Select(x => x.Parent.Element("Value").Value)
                      .FirstOrDefault() ?? "Not available";

That assumes I've understood you correctly, that you're just trying to get the text within the sibling "Value" element.

I don't think the null-coalescing (??) operator exists in VB, but you could take everything as far as FirstOrDefault, and then just have an "if it's nothing, set it to Not Available" check.

Upvotes: 1

Related Questions