While I was implementing an sorting code behind for the global navigation (or current), I found a defect in SharePoint 2010. The property web.Navigation.TopNavigationBar (or web.Navigation.QuickLaunch) always returns 0 items until you make a change through the UI (Site Action -> Site settings -> Navigation settings) and after that you can take action code behind and manipulate the sorting.
I needed to do it all without any interaction with the UI. To do this I had to add only the first time all nodes into the SPNavigationNodeCollection.
Show/Hidden csharp code
//This block fixes the SharePoint defect ------------------------
var count = (from SPNavigationNode node in NavigationNodes
where string.Compare(node.Properties["NodeType"] as string, "Area", true) == 0
select node).Count();
if (count < pweb.GetPublishingWebs().Count)
{
Dictionary<string, SPNavigationNode> nodeHash = new Dictionary<string, SPNavigationNode>();
foreach (SPNavigationNode node in NavigationNodes)
nodeHash.Add(node.Url, node);
foreach (PublishingWeb subweb in pweb.GetPublishingWebs())
{
if (!nodeHash.ContainsKey(subweb.Url))
{
string relUrl = subweb.ParentPublishingWeb.Uri.MakeRelativeUri(subweb.Uri).ToString();
SPNavigationNode nn = SPNavigationSiteMapNode.CreateSPNavigationNode(
subweb.Title, relUrl, NodeTypes.Area,
(string.Compare(navigationType,"global",true)==0 ? web.Navigation.TopNavigationBar : web.Navigation.QuickLaunch));
nn.Update();
}
}
web.Update();
}