开发者

Umbraco 4.6+ - How to get all nodes by doctype in C#?

开发者 https://www.devze.com 2023-02-10 16:59 出处:网络
Using Umbraco 4.6+, is there a way to retrieve all nodes of a specific doctype in C#?I\'ve been looking in the umbraco.NodeFactory namespace, but haven\'t found anything of use yet.开发者_如何学CI was

Using Umbraco 4.6+, is there a way to retrieve all nodes of a specific doctype in C#? I've been looking in the umbraco.NodeFactory namespace, but haven't found anything of use yet.开发者_如何学C


I was just doing this today, something like the below code should work (using umbraco.presentation.nodeFactory), call it with a nodeId of -1 to get the root node of the site and let it work it's way down:

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);
    }
}


Supposing you only eventually need a couple of nodes of the particular type, it would be more efficient to use the yield keyword to avoid retrieving more than you have to:

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;
}

So your final call to get nodes by type will be:

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

So if you only want to get the first five, you can add .Take(5) to the end and you will only recurse through the first 5 results rather than pull out the whole tree.


Or a recursive approach:

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...
}


If you're just creating a razor scripting file to be used by a macro (Umbraco 4.7+), I found this shorthand particularly useful...

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

Hope this helps somebody!


In umbraco 7.0+ you can do it like this

foreach (var childNode in node.Children<ChildNodeType>())
{
...
}
0

精彩评论

暂无评论...
验证码 换一张
取 消