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.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With