linq-lambda中的and和or

当我们需要频繁的在lambda中使用 or 和 and操作的时候可以先声明这样一个类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;

namespace Project.Service.Infrastructure
{
public static class PredicateBuilder
{
///


/// 构造函数使用True时:单个AND有效,多个AND有效;单个OR无效,多个OR无效;混合时写在AND后的OR有效
///

///
public static Expression<Func<T, bool>> True() { return f => true; }
///
/// 构造函数使用False时:单个AND无效,多个AND无效;单个OR有效,多个OR有效;混合时写在OR后面的AND有效
///

///
public static Expression<Func<T, bool>> False() { return f => false; }

    public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> expr1,
                                                        Expression<Func<T, bool>> expr2)
    {
        var invokedExpr = Expression.Invoke(expr2, expr1.Parameters.Cast<Expression>());
        return Expression.Lambda<Func<T, bool>>
              (Expression.OrElse(expr1.Body, invokedExpr), expr1.Parameters);
    }

    public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> expr1,
                                                         Expression<Func<T, bool>> expr2)
    {
        var invokedExpr = Expression.Invoke(expr2, expr1.Parameters.Cast<Expression>());
        return Expression.Lambda<Func<T, bool>>
              (Expression.AndAlso(expr1.Body, invokedExpr), expr1.Parameters);
    }
}

}

在使用时我们需要先将类中方法实例化
var where = PredicateBuilder.True();
var where1 = PredicateBuilder.False();
我们可以得到两个委托函数为泛型,传入实体类
Expression<Func<T, bool>> where
Expression<Func<T, bool>> where1
如同类中方法介绍的那样
where可以创造出类似于
(条件1 and 条件2 and 条件3......)or(条件1 and 条件2 and 条件3......)
这样的lambda条件公式
where1可创造出类似于
(条件1 or条件2 or 条件3......)and(条件1 or 条件2 or 条件3......)
具体使用方法需要先声名
比如我们现在要做出or操作
我们也必需要借助and将or操作拼接到lambda上面去
where1 = PredicateBuilder.False();
where1 = where1.Or(x=>条件1);
where1 = where1.Or(x=>条件2);
......
where = where.And(where1);
最后将条件附加到要查询的实体类上面,注意,此实体类必须要跟
var where = PredicateBuilder.True();
var where1 = PredicateBuilder.False();
中的泛型T保持一致
_db.T.Where(where);

posted @   C#HelloWord!!!  阅读(26)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
点击右上角即可分享
微信分享提示