我怎么做递归linq函数

本文关键字:linq 函数 递归 | 更新日期: 2023-09-27 18:06:19

我想制作一个菜单,这是我的代码。我需要递归函数

        var newTopMenu = new TopMenuVm
        {
            TopMenus = (from amp in allMasterPages
                        orderby amp.DisplayOrder
                        select new TopMenuVm
                        {
                            DisplayOrder = amp.DisplayOrder,
                            Url = string.IsNullOrEmpty(amp.Url) ? GenerateUrl(amp.Page1.OrderBy(x => x.DisplayOrder).FirstOrDefault()) : amp.Url,
                            PageId = amp.PageId,
                            PageTitle = amp.PageTitle,
                            TopMenus = (from submenu in amp.Page1
                                        orderby amp.DisplayOrder
                                        select new TopMenuVm
                                        {
                                            DisplayOrder = submenu.DisplayOrder,
                                            PageTitle = submenu.PageTitle,
                                            PageId = submenu.PageId,
                                            Url = string.IsNullOrEmpty(submenu.Url) ? GenerateUrl(submenu) : submenu.Url,
                                        }).ToList()//Here is go on infinite...,
                        }).ToList()
        };

我怎么做递归linq函数

您正在寻找这样的东西吗?

// allMasterPages is type List<MyPage> - change to whatever it really is
Func<List<MyPage>, List<TopMenuVM>> funcTopMenuVM = null;
funcTopMenuVM = ((pages) => {
    return
        (from amp in pages
            orderby amp.DisplayOrder
            select new TopMenuVM()
            {
                DisplayOrder = amp.DisplayOrder,
                Url = string.IsNullOrEmpty(amp.Url) ? GenerateUrl(amp.Page1.OrderBy(x => x.DisplayOrder).FirstOrDefault()) : amp.Url,
                PageId = amp.PageId,
                PageTitle = amp.PageTitle,
                TopMenus = funcTopMenuVM(amp.Page1)
            }).ToList();
});
var newTopMenu = new TopMenuVM()
{
    TopMenus = funcTopMenuVM(allMasterPages)
};

当然,它不一定是一个Func<>,它可以只是一个返回List并获取List