1. 程式人生 > >C# 根據節點深度建立頂層選單和相應子選單

C# 根據節點深度建立頂層選單和相應子選單

/// <summary>
/// 建立頂層選單集合
/// </summary>
/// <param name="menuItms">所有選單集合</param>
/// <returns>頂層選單集合</returns>
public IList<Sys_MenuItm> CreateTopMenuTree(IList<Sys_MenuItm> menuItms)
{
    if (menuItms == null || menuItms.Count < 1)
    {
        return null;
    }

    // 找到頂層 MenuItm
    IList<Sys_MenuItm> topMenuItms = menuItms.Where(it => it.Depth == 1).ToList();

    // 建立子選單集合
    for (int i = 0; i < topMenuItms.Count; i++)
    {
        CreateChildMenuItem(topMenuItms[i], menuItms);
    }
    return topMenuItms;
}

/// <summary>
/// 建立子選單
/// </summary>
/// <param name="parentMenu">父選單</param>
/// <param name="menuItms">子選單集合</param>
private void CreateChildMenuItem(Sys_MenuItm parentMenu, IList<Sys_MenuItm> menuItms)
{
    if (parentMenu == null || menuItms == null)
    {
        return;
    }

    IList<Sys_MenuItm> childMenus = menuItms.Where(it => it.ParentMenuCode == parentMenu.MenuCode).ToList();
    parentMenu.Children = childMenus;
    if (childMenus == null || childMenus.Count < 1)
        return;
    for (int i = 0; i < childMenus.Count; i++)
    {
        childMenus[i].Parent = parentMenu;
        CreateChildMenuItem(childMenus[i], menuItms);
    }
}