Sorting SitemapNodes based on the count of child elements
In an application i am reading from sitemap file adding it on to a SiteMapNodeCollection
Iterating through it and rendering the results based on some conditions.
But before passing on these SiteMapNodeCollection
for the manipulation i need to sort the nodes based on the number of childnodes(including if any sub child nodes).I thought of using Extension methods but am confused on using the same,as it is a hierarchial collection.
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 (Si开发者_高级运维teMapNode node in nodes)
{
//rendering based on condition.
}
could give me guidance on moving ahead.
You could write a method which calculates a subnodes count for the node specified like this:
private static int GetChildNodeCount(SiteMapNode node)
{
var nodeCount = node.ChildNodes.Count;
foreach (SiteMapNode subNode in node.ChildNodes)
{
nodeCount += GetChildNodeCount(subNode);
}
return nodeCount;
}
and then use it like this:
var orderedNodes = nodes.Cast<SiteMapNode>()
.OrderBy(n => GetChildNodeCount(n));
foreach (SiteMapNode node in orderedNodes)
{
//rendering based on condition.
}
精彩评论