Bogiecom.com
  • About
  • Magento
  • Sitecore
  • WordPress

Tree Menu Traversal in C# Queryable

Posted on January 19, 2017 by bc-admin

Using C# to query entire tree system of pages looking for a particular attribute.  Normally I would use a recursive technique, but then found this to be easier and more readable.  Not sure how it is on performance, I think it’s supposed to be better. Found it here http://stackoverflow.com/questions/7062882/searching-a-tree-using-linq#answer-7063002

Here’s how I implmented

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
    public class MenuItem
    {
        public virtual string NavigationTitle { get; set; }
        public virtual string Url { get; set; }
        public virtual bool ShowInMainNavigation { get; set; }
        public virtual bool ShowInFooterNavigation { get; set; }
        public virtual IEnumerable Children { get; set; }
        public virtual string TwitterHandle { get; set; }
        public virtual string FacebookHandle { get; set; }
        public virtual string InstagramHandle { get; set; }
 
        public IEnumerable GetDescendants(MenuItem root)
        {
 
            var nodes = new Stack(new[] { root });
            while (nodes.Any())
            {
                MenuItem node = nodes.Pop();
                yield return node;
                foreach (var n in node.Children) nodes.Push(n);
            }
 
        }
    }

Here’s how I used in Razor:

1
2
3
4
5
6
<ul>
@foreach (YourSite.Models.Common.MenuItem navItem in Model.GetDescendants(Model).Where(x => x.ShowInFooterNavigation == true))
{
@Html.Partial("~/Views/Shared/NavLink.cshtml", navItem)
}
</ul>

Posted in .NET, C#, Sitecore |
« Quick Way to Archive a WordPress Site

Pages

  • About
  • Magento
  • Sitecore
  • WordPress

Archives

  • January 2017
  • December 2013
  • November 2013
  • February 2013
  • January 2013
  • August 2012
  • July 2012
  • June 2012
  • May 2012
  • November 2011
  • March 2010
  • February 2010
  • January 2010
  • December 2009
  • November 2009
  • September 2009

Categories

  • .NET
  • Air Force
  • Apache Configuration
  • Bash
  • C#
  • Comma-Delimited
  • Custom Field Validator
  • Date Format
  • Dump Files
  • Files
  • Grep
  • Grooveshark
  • HTML
  • Image Resizing
  • Imagick
  • Integration
  • jQuery
  • Konami Code
  • Linux
  • Magento
  • Magento Third Party CMS Integration
  • Mini Shuttle
  • Miva Merchant 5.5
  • MySQL
  • PHP
  • Powershell
  • Regular Expressions
  • Rename-Item
  • Sed
  • Shell Scripting
  • Sitecore
  • Strings
  • Uncategorized
  • Updating Product Attributes
  • Video Games
  • Wordpress
  • X-37
  • XML
  • YUI Konami Event

CyberChimps WordPress Themes

© 2008 - 2016 Bogiecom.com