C# List<Func<T,bool>

C# List<Func<T,bool> 实现多条件选择器

以字符串为例

  List<Func<string, bool>> selectors = new List<Func<string, bool>>
            {
              param=>param.StartsWith("AAA"),//条件1
              param=>param.Contains("BBB"),//条件2
              param=>param.Contains("CCC")//条件3
            };
            bool result1 = selectors.Any(it => it("AAABBCCC"));//任意条件满足  true
            result1 = selectors.All(it => it("AAABBCCC"));//所以条件满足  false
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用以下代码实现: ```csharp public static Expression<Func<T, bool>> GetPredicate<T>(Expression<Func<T, bool>> predicate, List<int> input) { if (predicate == null) { var parameter = Expression.Parameter(typeof(T), "x"); var body = input.Select(i => Expression.Call( Expression.Property(parameter, "Id"), typeof(string).GetMethod("StartsWith", new[] { typeof(string) }), Expression.Constant(i.ToString()))).Aggregate<Expression, Expression>(null, (current, next) => current == null ? next : Expression.OrElse(current, next)); predicate = Expression.Lambda<Func<T, bool>>(body, parameter); } else { var parameter = predicate.Parameters.First(); var body = input.Select(i => Expression.Call( Expression.Property(parameter, "Id"), typeof(string).GetMethod("StartsWith", new[] { typeof(string) }), Expression.Constant(i.ToString()))).Aggregate<Expression, Expression>(null, (current, next) => current == null ? next : Expression.OrElse(current, next)); body = Expression.OrElse(predicate.Body, body); predicate = Expression.Lambda<Func<T, bool>>(body, parameter); } return predicate; } ``` 该方法接受一个 `Expression<Func<T, bool>>` 类型的参数 `predicate` 和一个 `List<int>` 类型的参数 `input`,并返回一个新的 `Expression<Func<T, bool>>` 类型的对象。 该方法首先判断 `predicate` 是否为 `null`,如果是,则使用 `input` 构造一个新的 lambda 表达式作为返回结果;如果不是,则将 `input` 构造出来的 lambda 表达式与原有的 `predicate` 进行逻辑或运算,得到一个新的 lambda 表达式作为返回结果。 注意,该方法的返回值是一个新的 `Expression<Func<T, bool>>` 类型的对象,原有的 `predicate` 对象并没有被修改。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值