tags:

views:

196

answers:

1

Hello, I am reading in from my web.sitemap file, and I would like to apply a Linq OrderBy command to the ChildNode elements. However, I can't seem to access the OrderBy method to the ChildNodes property unless I first cast it to SiteMapNode (which is dumb because it's already of type SiteMapNode). Please point me in the right direction.

Here is my code:

foreach (SiteMapNode childNode in node.ChildNodes.Cast<SiteMapNode>().OrderBy(x => x["name"]))
+1  A: 

Try this:

foreach (var childNode in node.ChildNodes.OrderBy(x => x.Key))

Replace x.Key with another property, if needed.

http://msdn.microsoft.com/en-us/library/system.web.sitemapnode%5Fmembers%28lightweight%29.aspx

Actually, SiteMapNodeCollection which ChildNodes implements IList, but is not the strongly-typed IList<SiteMapNode>. You will need the Cast.

See http://msdn.microsoft.com/en-us/library/system.web.sitemapnodecollection.aspx

You could always roll an extension method for SiteMapNodeCollection.

public static IEnumerable<SiteMapNode> OrderBy(this SiteMapNodeCollection smnc,
                                               Func<SiteMapNode, TKey> expression)
{
    return smnc.Cast<SiteMapNode>().OrderBy(expression);
}
Daniel A. White
OrderBy is not a method of ChildNodes property. But when I cast it, it is.
Mike C.
Thanks for the edit. This makes sense. Merry Christmas!
Mike C.
And you too Mike!
Daniel A. White