递归过滤Linq到对象

Cap*_*in0 2 c# linq

是否可以使用linq到对象递归过滤递归树中的所有项目.

这是我正在使用的模型.这是由另一个应用程序给我的

public class Menu
{
   public string Name{get;set;}
   public string Roles{get;set;}
   public List<Menu> Children{get;set;}
}
Run Code Online (Sandbox Code Playgroud)

当用户登录我的应用程序时,我需要根据菜单项中指定的角色检查用户角色.我知道我可以编写一个递归方法,使用for循环检查它.

无论如何我在那里使用像'MenuList.Where(..检查角色)

提前致谢

Kon*_*ski 5

我只是在Menu类中实现另一个方法:

public class Menu
{
    public string Name { get; set; }
    public string Roles { get; set; }
    public List<Menu> Children { get; set; }
    /// <summary>
    /// Checks whether this object or any of its children are in the specified role
    /// </summary>        
    public bool InRole(string role)
    {
        if (role == null)
        {
            throw new ArgumentNullException("role");
        }
        var inRole = (this.Roles ?? String.Empty).Contains(role);
        if (!inRole & Children != null)
        {
            return Children.Any(child => child.InRole(role));
        }
        return inRole;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后您可以编写LINQ查询,例如:

var inRole = menuList.Where(menu => menu.InRole("admin"));
Run Code Online (Sandbox Code Playgroud)

它会递归地工作.