2011-02-16 40 views

回答

16

我今天剛剛這樣做,像下面的代碼應該工作(使用umbraco.presentation.nodeFactory),調用它的nodeId爲-1以獲得網站的根節點,讓它工作的方式下來:

private void DoSomethingWithAllNodesByType(int NodeId, string typeName) 
{ 
    var node = new Node(nodeId); 
    foreach (Node childNode in node.Children) 
    { 
     var child = childNode; 
     if (child.NodeTypeAlias == typeName) 
     { 
      //Do something 
     } 

     if (child.Children.Count > 0) 
      GetAllNodesByType(child, typeName); 
    } 
} 
+0

使用-1作爲ID來獲得網站的根節點是一個偉大的小費!感謝那 – ComethTheNerd 2012-12-12 10:41:54

3

或者遞歸的方法:

using umbraco.NodeFactory; 

private static List<Node> FindChildren(Node currentNode, Func<Node, bool> predicate) 
{ 
    List<Node> result = new List<Node>(); 

    var nodes = currentNode 
     .Children 
     .OfType<Node>() 
     .Where(predicate); 
    if (nodes.Count() != 0) 
     result.AddRange(nodes); 

    foreach (var child in currentNode.Children.OfType<Node>()) 
    { 
     nodes = FindChildren(child, predicate); 
     if (nodes.Count() != 0) 
      result.AddRange(nodes); 
    } 
    return result; 
} 

void Example() 
{ 
    var nodes = FindChildren(new Node(-1), t => t.NodeTypeAlias.Equals("myDocType")); 
    // Do something... 
} 
15

假如你最終只需要幾個特定類型的節點,這將是更有效地使用yield關鍵字,以避免超過您獲取更多必須:

public static IEnumerable<INode> GetDescendants(this INode node) 
{ 
    foreach (INode child in node.ChildrenAsList) 
    { 
     yield return child; 

     foreach (INode grandChild in child.GetDescendants()) 
     { 
      yield return grandChild; 
     } 
    } 
    yield break; 
} 

因此,最終的調用來獲取按類型節點將是:

new Node(-1).GetDescendants().Where(x => x.NodeTypeAlias == "myNodeType") 

所以,如果你只是想獲得第5名,您可以添加。取(5)到最後,你會只通過前5個結果遞歸而不是拉出整棵樹。

1

如果你只是建立一個剃鬚刀腳本文件,由宏(一把umbraco 4.7+)被使用,我發現這個速記特別有用...

var nodes = new Node(-1).Descendants("DocType").Where("Visible"); 

希望這有助於有人!

1

在一把umbraco 7.0或更高版本,你可以做這樣的

foreach (var childNode in node.Children<ChildNodeType>()) 
{ 
... 
} 
相關問題