Linq 多条件查询组合问题

借助老外写的一个扩展表达式的类,可以把上篇中的代码写得更优雅

这是PredicateBuilder的源文件

 public static class PredicateBuilder
    {
      public static Expression> True ()  { return f => true;  }
      public static Expression> False () { return f => false; }
     
      public static Expression> Or (this Expression> expr1,
                                                          Expression> expr2)
      {
        var invokedExpr = Expression.Invoke (expr2, expr1.Parameters.Cast ());
        return Expression.Lambda>
              (Expression.Or (expr1.Body, invokedExpr), expr1.Parameters);
      }
     
      public static Expression> And (this Expression> expr1,
                                                           Expression> expr2)
      {
        var invokedExpr = Expression.Invoke (expr2, expr1.Parameters.Cast ());
        return Expression.Lambda>
              (Expression.And (expr1.Body, invokedExpr), expr1.Parameters);
      }
    }

下面是使用示例 :

List GetProductsByAND(params string[] keywords) 
    {
        DBDataContext db = new DBDataContext(Database.ConnectionString);
        IQueryable query = db.Products;
        foreach (string keyword in keywords)
        {
            string temp = keyword;
            query = query.Where(p => p.Description.Contains(temp));
        }
        //翻译后的sql语句:
        //Select [t0].[ID], [t0].[Name], [t0].[Description]
        //FROM [dbo].[Product] AS [t0]
        //Where ([t0].[Description] LIKE '%手机%') AND ([t0].[Description] LIKE '%6111%')
        return query.ToList();   
    }


    List GetProductsByOR(params string[] keywords)
    {
        DBDataContext db = new DBDataContext(Database.ConnectionString);
        var predicate = PredicateBuilder.False();
        foreach (string keyword in keywords)
        {
            string temp = keyword;
            predicate = predicate.Or(p => p.Description.Contains(temp));
        }
        var query = db.Products.Where(predicate);
        //翻译后的sql语句:
        //Select [t0].[ID], [t0].[Name], [t0].[Description]
        //FROM [dbo].[Product] AS [t0]
        //Where ([t0].[Description] LIKE '%6111%') OR ([t0].[Description] LIKE '%2350%')
        return query.ToList();
    }

    void ShowData() 
    {
        //var _products = GetProductsByOR("6111", "2350");
        //Repeater1.DataSource = _products;
        //Repeater1.DataBind();

        var predicate = PredicateBuilder.True();

        string _name = "6111";
        if (!string.IsNullOrEmpty(_name)) 
        {
            predicate = predicate.And(p => p.Name.Contains(_name));
        }

        string _description = "长虹";
        if (!string.IsNullOrEmpty(_description)) 
        {
            predicate = predicate.And(p => p.Description.Contains(_description));
        }

        using (DBDataContext db = new DBDataContext(Database.ConnectionString))
        {
            var _Products = db.Products.Where(predicate);
            Repeater1.DataSource = _Products;
            Repeater1.DataBind();
        }

    }

我的代码:

	var bproductwhere = PredicateBuilder.True();
					//工厂名称
					if (!string.IsNullOrEmpty(strParm[0]))
					{
						bproductwhere = bproductwhere.And(p => p.工厂名称 == strParm[0]);
					}
					//出库日期
					if (!string.IsNullOrEmpty(strParm[1]))
					{
						if (string.IsNullOrEmpty(strParm[0]))
						{
							bproductwhere = bproductwhere.And(p => p.工厂名称 == context.Server.UrlDecode
											(context.Request.Cookies["UserLogin"]["ClientName"]));
						}
						string[] strDate = strParm[1].Split('-');
						bproductwhere = bproductwhere.And(p => Convert.ToDateTime(p.出库日期) >= Convert.ToDateTime(strDate[0])
									&& Convert.ToDateTime(p.出库日期) < Convert.ToDateTime(strDate[1]).AddDays(1));
					}
					//品番
					if (!string.IsNullOrEmpty(strParm[2]))
					{
						bproductwhere = bproductwhere.And(p => p.品番 == strParm[2]);
					}

原文地址:http://www.cnblogs.com/yjmyzz/archive/2008/03/25/1122135.html 感谢

http://developer.51cto.com/art/200909/151931.htm   简单解决Linq多条件组合问题

http://blog.csdn.net/zhensoft163/article/details/7408788 Linq to sql 实现多条件的动态查询(方法一) 

http://blog.csdn.net/zhensoft163/article/details/7455875 Linq to sql 实现多条件的动态查询(方法二)




你可能感兴趣的:(LINQ,And,SQL,Server,.NET,And,C#)