Linq动态查询
2018-05-08 17:54 会飞的雪鹿 阅读(217) 评论(0) 编辑 收藏 举报![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public class ExpressionCall { List<Customer> customers = new List<Customer>() { new Customer() { CustomerID = "A001"}, new Customer() { CustomerID = "A"}, new Customer() { CustomerID = "B001" }, }; string[] starts = { "A", "C", "D" }; public void SelectMore() { //根据CustomerID首字母 包含A,C,D动态创建查询 IQueryable<Customer> cus = customers.AsQueryable(); ParameterExpression c = Expression.Parameter(typeof(Customer), "c"); Expression condition = Expression.Constant(false); foreach (string s in starts) { Expression con = Expression.Call( Expression.Property(c, typeof(Customer).GetProperty("CustomerID")), typeof(string).GetMethod("Equals", new Type[] { typeof(string) }), Expression.Constant(s)); condition = Expression.Or(con, condition); } Expression<Func<Customer, bool>> end = Expression.Lambda<Func<Customer, bool>>(condition, new ParameterExpression[] { c }); var cu = cus.Where(end); } } public class Customer { public string CustomerID { get; set; } }
代码如上,参考:http://www.cnblogs.com/blusehuang/archive/2007/07/13/816970.html
其中包含。首字母包含
typeof(string).GetMethod("StartsWith", new Type[] { typeof(string) }),
typeof(string).GetMethod("Contains", new Type[] { typeof(string) }),