【问题标题】:Recursive Filtering Linq To Objects递归过滤 Linq 到对象
【发布时间】:2012-08-06 11:42:31
【问题描述】:

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

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

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

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

无论如何我都可以使用 'MenuList.Where(..check the roles)

提前致谢

【问题讨论】:

  • 所以您想返回一个新的Menu,它的子项根据用户的角色和MenuRoles 过滤(递归)?
  • 是的,先生,这是要求

标签: c# linq


【解决方案1】:

我只是在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"));

它将递归地工作。

【讨论】:

    【解决方案2】:

    试试这个扩展方法:

    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));
    

    【讨论】:

      猜你喜欢
      • 2016-11-03
      • 2020-09-26
      • 2019-09-15
      • 1970-01-01
      • 1970-01-01
      • 2011-12-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多