首页 > 代码库 > Dynamic Linq 不支持模糊查询...
Dynamic Linq 不支持模糊查询...
转发。。。
http://www.blogjava.net/jvict/articles/246939.html
中文的实在是找不到了,在MS的官方BBS上找到了个链接
这里放出核心代码,很容易看懂,简单就是美!
1 searchPredicate = PredicateExtensions.True<UserT_TractInfo>();
2 foreach (string key in nvcParam)
3 {
4 string condition = string.Empty;
5 switch (key)
6 {
7 case "b_number":
8 condition = nvcParam[key];
9 searchPredicate = searchPredicate.And(u => u.B_number.Contains(condition));
10 break;
11 case "b_address":
12 condition = nvcParam[key];
13 searchPredicate = searchPredicate.And(u => u.B_address.Contains(condition));
14 break;
15 case "b_canton":
16 condition = nvcParam[key];
17 searchPredicate = searchPredicate.And(u => u.B_canton.Contains(condition));
18 break;
19 case "a_status":
20 condition = nvcParam[key];
21 searchPredicate = searchPredicate.And(u => u.A_status.ToString().Contains(condition));
22 break;
23 case "b_area":
24 condition = nvcParam[key];
25 searchPredicate = searchPredicate.And(u => u.B_area.Contains(condition));
26 break;
27 case "c_clinchdate":
28 condition = nvcParam[key];
29 searchPredicate = searchPredicate.And(u => u.C_clinchdate.Contains(condition));
30 break;
31 default:
32 break;
33 }
34 }
35
36 return Consulting.Instance.UserT_TractInfo.Where(searchPredicate).OrderByDescending(t => t.ID).Skip(startIndex - 1).Take(pageSize).ToList();
下面是我写了注释后的PredicateExtensions,我说不清楚构造函数的True和False具体是怎么起作用的,但结果就是我的注释那样,在复合查询写条件时很重要(不过目前全写AND就完成复合查询了,我还没搞多关键词OR的那种):
1 /// <summary>
2 /// 构造函数使用True时:单个AND有效,多个AND有效;单个OR无效,多个OR无效;混合时写在AND后的OR有效
3 /// 构造函数使用False时:单个AND无效,多个AND无效;单个OR有效,多个OR有效;混合时写在OR后面的AND有效
4 /// </summary>
5 public static class PredicateExtensions
6 {
7 public static Expression<Func<T, bool>> True<T>() { return f => true; }
8
9 public static Expression<Func<T, bool>> False<T>() { return f => false; }
10
11 public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> expression1, Expression<Func<T, bool>> expression2)
12 {
13 var invokedExpression = Expression.Invoke(expression2, expression1.Parameters.Cast<Expression>());
14
15 return Expression.Lambda<Func<T, bool>>(Expression.Or(expression1.Body, invokedExpression), expression1.Parameters);
16 }
17
18 public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> expression1, Expression<Func<T, bool>> expression2)
19 {
20 var invokedExpression = Expression.Invoke(expression2, expression1.Parameters.Cast<Expression>());
21
22 return Expression.Lambda<Func<T, bool>>(Expression.And(expression1.Body, invokedExpression), expression1.Parameters);
23 }
24 }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。