递归过滤Linq到对象

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

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

public class Menu { public string Name{get;set;} public string Roles{get;set;} public List Children{get;set;} } 

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

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

提前致谢

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

 public class Menu { public string Name { get; set; } public string Roles { get; set; } public List Children { get; set; } ///  /// Checks whether this object or any of its children are in the specified role ///  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; } } 

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

 var inRole = menuList.Where(menu => menu.InRole("admin")); 

它会递归地工作。

试试这个扩展方法:

 public static IEnumerable Flatten(this IEnumerable source, Func recursion) where R : IEnumerable { return source.SelectMany(x => (recursion(x) != null && recursion(x).Any()) ? recursion(x).Flatten(recursion) : null) .Where(x => x != null); } 

你可以像这样使用它:

 menu.Flatten(x => x.Children).Where(x => x.Roles.Contains(role));