有没有一种方法可以在C#中检索特定文档类型的所有节点?我一直在寻找umbraco.NodeFactory
名称空间,但还没有找到任何有用的东西。
发布于 2011-02-17 02:26:44
我今天就是这样做的,下面的代码应该可以工作(使用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);
}
}
发布于 2011-12-03 01:39:28
假设您最终只需要几个特定类型的节点,那么使用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个结果,你可以在最后加上.Take(5),这样你就只会递归前5个结果,而不是把整个树都拉出来。
发布于 2011-08-12 18:08:11
或者是递归方法:
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...
}
https://stackoverflow.com/questions/5019205
复制相似问题