1. 程式人生 > >linq to sql where 多條件 or and

linq to sql where 多條件 or and

using System.Linq.Expressions;
public static class PredicateBuilder
{
    public static Expression<Func<T, bool>> True<T>() { return f => true; }
    public static Expression<Func<T, bool>> False<T>() { return f => false; }
    //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.Or(expr1.Body, invokedExpr), expr1.Parameters);
    }
    //true
    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.And(expr1.Body, invokedExpr), expr1.Parameters);
    }
}


---------------------------------------
var list = db.t_schedule;//from t in db.テーブル名 select t;
//True:And検索/False:Or検索
var where = PredicateBuilder.False<テーブル名 >();
if (!string.IsNullOrEmpty(検索條件1))
{
    where = where.Or(p => p.カラム1 == 検索條件1);
}
if (!string.IsNullOrEmpty(検索條件2))
{
    where = where.Or(p => p.カラム2 == 検索條件2);
}
var result = list.Where(where.Compile()).ToList();