LINQ字符拼接的AND和OR操作
最近项目经常涉及LINQ的AND和OR操作,顺便收集了一下资料
AND操作:
var query=....; if (!string.IsNullOrEmpty(a)) { query = query.Where(p => p.name == a); }
OR操作:
第一种:
public static class PredicateBuilder { /// <summary> /// 构造函数使用True时:单个AND有效,多个AND有效;单个OR无效,多个OR无效;混合时写在AND后的OR有效 /// 构造函数使用False时:单个AND无效,多个AND无效;单个OR有效,多个OR有效;混合时写在OR后面的AND有效 /// </summary> public static Expression<Func<T, bool>> True<T>() { return f => true; } public static Expression<Func<T, bool>> False<T>() { 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.Or(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.And(expr1.Body, invokedExpr), expr1.Parameters); } public static Predicate<T> ConvertToPredicate<T>(this Func<T, bool> func) { return new Predicate<T>(func); } }
使用方法:
sql语句的想要实现的内容如下,重点关注where后面的条件部分: select ... from ... where (Test.id = 3 and Test.name = "N3") or (Test.id = 4 and Test.name = "N4") linq方式的动态实现如下: var predicate = PredicateBuilder.False<Test>(); foreach (var keyword in searchKeywords) { int nTemp = keyword.id; string sTemp = keyword.name; predicate = predicate.Or(p => p.id == nTemp && p.name == sTemp); } IEnumerable<Test> results = lst.Where(predicate.Compile());
第二种:
var q1 = from u in query.Users where u.name== a && a != "" || u.age == b && b != "" || u.sex == c && c != "" || u.address ==d && d !="" select u; q1.ToList();
第三种:
var query=...; var basequery=...; foreach(var seq in condictions) { query=query.union(basequery.where(a=>a.name.contains("xxx")); }
注明一下出处:
http://www.cnblogs.com/jack98/p/3237565.html
http://blog.sina.com.cn/s/blog_93ac501e010144se.html
http://www.silverlightchina.net/html/tips/2011/0814/9741.html