在一个应用程序中,我正在读取站点地图文件,将其添加到 SiteMapNodeCollection
中,遍历它并根据某些条件呈现结果。
但在传递这些 SiteMapNodeCollection
进行操作之前,我需要根据子节点的数量(包括任何子子节点)对节点进行排序。我想过使用扩展方法,但对使用相同,因为它是一个分层集合。
SiteMapDataSourceView siteMapView = (SiteMapDataSourceView)siteMapData.GetView(string.Empty);
//Get the SiteMapNodeCollection from the SiteMapDataSourceView
SiteMapNodeCollection nodes = (SiteMapNodeCollection)siteMapView.Select(DataSourceSelectArguments.Empty);
***//Need to sort the nodes based on the number of child nodes it has over here.***
//Recursing through the SiteMapNodeCollection...
foreach (SiteMapNode node in nodes)
{
//rendering based on condition.
}
可以给我前进的指导。
最佳答案
您可以编写一个方法来计算指定节点的子节点数,如下所示:
private static int GetChildNodeCount(SiteMapNode node)
{
var nodeCount = node.ChildNodes.Count;
foreach (SiteMapNode subNode in node.ChildNodes)
{
nodeCount += GetChildNodeCount(subNode);
}
return nodeCount;
}
然后像这样使用它:
var orderedNodes = nodes.Cast<SiteMapNode>()
.OrderBy(n => GetChildNodeCount(n));
foreach (SiteMapNode node in orderedNodes)
{
//rendering based on condition.
}
关于c# - 根据子元素的数量对 SitemapNodes 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5472137/