podeig
podeig

Reputation: 2741

Find parent with defined attribute wuth LINQ

I have variable XElement content =

        "...
         <item text="Name-1" id="1" segment="1" secret-id="Find-Me">
            <item text="Name-1-1" id="1.1">
               <item text="Name-1-1-1" id="1.1.1" />
               <item text="Name-1-1-2" id="1.1.2" />
            </item>
         </item>
         ..."

I have also an item with id = 1.1.2

I need to find the first parent of this item which has attribute segment="1" and get its secret-id

How to do this with LINQ?

Upvotes: 1

Views: 1075

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1500555

You mean the "closest ancestor"?

string secretId = element.Ancestors()
                         .Where(x => (string) x.Attribute("segment") == "1")
                         .Select(x => (string) x.Attribute("secret-id"))
                         .FirstOrDefault();

The result will be null if either:

  • There are no ancestors with an attribute segment="1"
  • The element with that attribute has no secret-id attribute.

Upvotes: 2

SLaks
SLaks

Reputation: 887453

Like this:

item.Ancestors().Select(p => p.Attribute("secret-id")).First(a => a != null)

Upvotes: 1

Related Questions