Get All Nodes By DocumentType

The following code describes how to get all the nodes by a particular document type across the whole Umbraco site. It uses a recursive method so if you add this as a macro I would suggest caching to reduce the number of times this method runs.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using umbraco.presentation.nodeFactory;


public class UmbracoHelper
{
    private const int CONST_NODEAMOUNT = 10;
    /// <summary>
    /// Get all nodes by type, put -1 to start at the root of the website
    /// </summary>
    /// <param name="NodeId"></param>
    /// <param name="typeName"></param>
    /// <returns></returns>
    public static List<Node> GetAllNodesByType(int NodeId, string typeName)
    {
        List<Node> foundNodes = new List<Node>();
        var node = new Node(NodeId);
        foreach (Node childNode in node.Children)
        {
            var child = childNode;
            if (child.NodeTypeAlias == typeName)
            {
                foundNodes.Add(child);
            }

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

        //Take the first 10, this can be changed
        return foundNodes.Take(CONST_NODEAMOUNT).ToList();
    }

    /// <summary>
    /// Recursive method to get the nodes from the child passed in as a parameter
    /// </summary>
    /// <param name="foundNodes"></param>
    /// <param name="node"></param>
    /// <param name="typeName"></param>
    private static void GetAllNodesByType(ref List<Node> foundNodes, Node node, string typeName)
    {
     
        foreach (Node childNode in node.Children)
        {
            var child = childNode;
            if (child.NodeTypeAlias == typeName)
            {
                foundNodes.Add(child);
            }

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

   
    public UmbracoHelper()
    {
       
    }
}