Csharp/C#教程:递归过滤Linq到对象分享


递归过滤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); } 

你可以像这样使用它:

上述就是C#学习教程:递归过滤Linq到对象分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

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

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/1015059.html

(0)
上一篇 2021年12月30日
下一篇 2021年12月30日

精彩推荐