如何让AuthorizationRuleCollection支持LINQ的Exist方法检测特定访问规则?
这问题我之前也碰到过,AuthorizationRuleCollection属于.NET里的老派非泛型集合,本身没实现IEnumerable<T>,所以没法直接用LINQ的标准方法。不过咱们通过扩展方法就能轻松搞定,这里有两种方案供你选择:
方案一:先转泛型序列,复用所有LINQ方法
先写一个扩展方法把非泛型的AuthorizationRuleCollection转换成泛型的IEnumerable<AuthorizationRule>,这样你就能直接用LINQ的Any方法(这其实就是LINQ版的Exists),还能顺便用上其他LINQ功能比如Where、Select:
using System.Collections.Generic; using System.Web.Configuration; // 注意引入命名空间,AuthorizationRule在这里 public static class AuthorizationRuleCollectionExtensions { // 将AuthorizationRuleCollection转为泛型可枚举序列 public static IEnumerable<AuthorizationRule> AsEnumerable(this AuthorizationRuleCollection rules) { if (rules == null) throw new ArgumentNullException(nameof(rules)); foreach (AuthorizationRule rule in rules) { yield return rule; } } }
使用的时候就像这样:
// 假设你已经拿到了AuthorizationRuleCollection实例 AuthorizationRuleCollection authRules = ...; // 检查是否存在Identity为"identifier"的规则 bool hasTargetRule = authRules.AsEnumerable().Any(r => r.Identity == "identifier");
方案二:直接实现专属的Exists扩展方法
如果你就想要一个命名为Exists的方法,完全可以直接写一个针对性的扩展,逻辑和Any类似,但命名更贴合你的需求:
using System; using System.Web.Configuration; public static class AuthorizationRuleCollectionExtensions { public static bool Exists(this AuthorizationRuleCollection rules, Func<AuthorizationRule, bool> predicate) { // 空值检查,避免空引用异常 if (rules == null) throw new ArgumentNullException(nameof(rules)); if (predicate == null) throw new ArgumentNullException(nameof(predicate)); // 遍历集合,找到第一个符合条件的项就返回true foreach (AuthorizationRule rule in rules) { if (predicate(rule)) return true; } // 遍历完都没找到就返回false return false; } }
使用时就和你预想的一样:
bool exists = authRules.Exists(r => r.Identity == "identifier");
小提示
两种方案里,方案一更灵活——转成泛型序列后,你能解锁所有LINQ的强大功能;方案二则更直观,完全匹配你想要的Exists调用方式,选哪种全看你的实际需求。
内容的提问来源于stack exchange,提问作者Thypari
相关产品推荐
相关产品推荐

