Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order menu nodes by parent, previous and next id

Tags:

c#

I have a small menu which I would like to order by the DB table id like the following:

  public class Obj
    {
        public string Value { get; set; }
        public int? ParentNodeId { get; set; }
        public int? PreviousNodeId { get; set; }
        public int? NextNodeId { get; set; }
    }

 private IEnumerable<MenuNodeDTO> GetSortedMenuNodes(int menuId)
    {
        var nodes = LoadMenuNodes(menuId);
        foreach (MenuNode menuNode in nodes
            .Where(s => s.MenuItemId == null && s.ParentNodeId == null)
            .OrderBy(x => x?.PreviousNodeId)
            .Where(x => x.PreviousNodeId != x.Id))
        {
            MenuNodeDTO tmpMenuNode = new MenuNodeDTO();
            tmpMenuNode.MenuNodeDtoId = menuNode.Id;
            tmpMenuNode.MenuItemCode = menuNode.MenuItem?.Code;
            tmpMenuNode.ChildMenuNodes = GetChildNodes(menuNode).ToList();
            tmpMenuNode.MenuSettings = GetMenuSettings(menuNode).ToList();
            yield return tmpMenuNode;
        }
}

Example:

Id = 1 MainMenuPoint1 ParentNodeId = null, PreviousNodeId = null, NextNodeId = 4
Id = 2 -> 1 ChildNodeFromPoint1 ParentNodeId = 1, PreviousNodeId = null, NextNodeId = null
Id = 3  --> ChildNodeFromFirstChildNode1 ParentNodeId = 2, PreviousNodeId = null, NextNodeId = null
Id = 4 MainMenuPoint2 ParentNodeId = null, PreviousNodeId = 1, NextNodeId = null

The problem with my for each is that when the id changed the ordering not works. Has someone a idea how to order by parentid, previousid and next id which check every time all ids for the relationship?

like image 698
kb_ Avatar asked Nov 09 '22 05:11

kb_


1 Answers

 private IEnumerable<MenuNodeDTO> GetSortedNodes(Menu menu, MenuNode node)
        {
            List<MenuNodeDTO> items = new List<MenuNodeDTO>();

            var nodes = node != null ? node.ChildMenuNodes : menu.MenuNodes;
            var nextNode = node == null
                ? nodes.Where(c => c.PreviousNodeId == null && c.ParentNodeId == null).FirstOrDefault()
                : nodes.Where(c => c.ParentNodeId == node.Id && c.PreviousNodeId == null).FirstOrDefault();

            while (nextNode != null)
            {
                MenuNodeDTO tmpMenuNode = new MenuNodeDTO();
                tmpMenuNode.MenuNodeDtoId = nextNode.Id;
                tmpMenuNode.MenuItemCode = nextNode?.MenuItem?.Code;
                tmpMenuNode.ChildMenuNodes = this.GetSortedNodes(menu, nextNode).ToList();
                tmpMenuNode.MenuSettings = GetMenuSettings(nextNode).ToList();
                items.Add(tmpMenuNode);
                if (!nextNode.NextNodeId.HasValue) break;
                nextNode = nextNode.NextNode;
            }
            return items;
        }
like image 69
kb_ Avatar answered Nov 14 '22 23:11

kb_