c# - 根据子元素的数量对 SitemapNodes 进行排序

标签 c# asp.net collections sitemap

在一个应用程序中,我正在读取站点地图文件,将其添加到 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/

相关文章:

java - 如何从 Java 列表中删除所有重复的字符串?

c# - 如何摆脱错误 : "Data source name not found and no default driver specified" in . 网络?

c# - 当 FormBorderStyle 设置为 None 时 winforms 绘制边框并 move

c# - 控制台应用程序打印 "Fail:"

c# - 使用 sqldatareader 的下拉列表

c# - 优化 list<T>.Sort(Comparer)

c# - 如何按照上次在 asp.net-webpages 中修改的日期顺序对 .GetFiles() 中的字符串数组进行排序?

asp.net - 尝试使用 MVC 4 自定义错误页面找出奇怪的行为。有时我的自定义错误页面会在 404 页面上被绕过

javascript - 绑定(bind) Javascript 按键事件

c# - IEnumerable <T>的AddItem的C#扩展方法