Reputation: 2741
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
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:
Upvotes: 2
Reputation: 887453
Like this:
item.Ancestors().Select(p => p.Attribute("secret-id")).First(a => a != null)
Upvotes: 1