从子列表中获取对象C#

时间:2018-07-06 20:40:42

标签: c# asp.net linq

我很难做这样的事情: Get list from a sublist

考虑

Class Menu
{
    int Id;
    string Name;
    bool IsActive;
    List<Menu> SubMenus;
}

List<Menu> someList;

我想根据ID从someList.SubMenus获取一项,并更新其Name属性。

我现在所做的一切:

var objectToUpdate = viewModel.menuSubMenuTreeList.Where(x => x.SubMenus.Where(y => y.MenuID == subMenuId).Any()).FirstOrDefault();

它似乎不起作用。谢谢!

2 个答案:

答案 0 :(得分:1)

您已根据条件过滤了父项。您唯一缺少的是获取子项:

C#7:

var objectToUpdate = viewModel.menuSubMenuTreeList
                     .Where(x => x.SubMenus.Where(y => y.MenuID == subMenuId).Any())
                     .FirstOrDefault()?.SubMenus.Where(y => y.MenuID == subMenuId);

早期版本:

var found = viewModel.menuSubMenuTreeList
                     .Where(x => x.SubMenus.Where(y => y.MenuID == subMenuId).Any())
                     .FirstOrDefault();

var objectToUpdate = found != null ? found.SubMenus.Where(y => y.MenuID == subMenuId) : null;

答案 1 :(得分:0)

您可以使用SelectMany将所有子菜单归为一个列表:

var submenus = someList.SelectMany( x => x.SubMenus );

从那里可以找到子菜单:

var submenu = submenus.Where( x => x.Id == subMenuId );

并设置其名称:

submenu.Name = "SomeName";

将它们放在一起:

someList
    .SelectMany
    ( 
        x => x.SubMenus 
    )
    .Where
    (
        x => x.Id == subMenuId
    )
    .Name = "SomeName";