递归过滤Linq到对象

时间:2012-08-06 11:42:32

标签: c# linq

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

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

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

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

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

来使用它

提前致谢

2 个答案:

答案 0 :(得分: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;
    }
}

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

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

它将以递归方式工作。

答案 1 :(得分:1)

尝试此扩展方法:

public static IEnumerable<T> Flatten<T, R>(this IEnumerable<T> source, Func<T, R> recursion) where R : IEnumerable<T>
{
    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));