簡體   English   中英

Linq to XML,更簡單的選擇層次結構中深度級別最高的元素的方法

[英]Linq to XML, simpler way to select element with highest depth level in hierarchy

我正在嘗試選擇層次結構中深度最高(嵌套最多)的元素。

        var elems = my_list.Elements()
            .Where(x => x.Attribute("Name") != null && x.Attribute("Name").Value == "John")
            ;

有沒有比這更簡單的方法,以及過濾?

    XElement elem2 = null;
    int i = 0;
    foreach (var elem in elems)
    {
        var depth = elem.AncestorsAndSelf().Count();
        if(depth >= i)
        {
            i = depth;
            elem2 = elem;
        }
    }

您可以將MaxBy() (來自 .NET 6 或來自MoreLinq 包)與您的祖先計數一起使用:

// Note the change to use Descendants, as otherwise only direct
// children will be returned, which will all have the same "level"
var element = list.Descendants()
    .Where(x => (string) x.Attribute("Name") == "John")
    .MaxBy(x => x.AncestorsAndSelf().Count());

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM