LINQ模糊查詢學習體驗淺析
LINQ模糊查詢來實現復合搜索的功能,具體的操作過程是什么呢?在這里向你介紹一下處理過程,使用LINQ模糊查詢有什么需要注意的呢?那么我們通過這個例子希望對你有所啟發。
LINQ模糊查詢實現的多條件復合搜索效果如下圖:
LINQ模糊查詢實現階段一:
首先是找到了李永京(YJingLee)前輩的《LINQ體驗(17)——LINQ to SQL語句之動態查詢》一文,利用Lambda表達式樹可以進行動態查詢。寫了個方法進行復合查詢,動態組合條件,生成Lambda表達式。
- /// <summary>
- /// 這個方法帶分頁功能,通過輸入的鍵值對NVC進行復合查詢
- /// </summary>
- List<UserT_TractInfo> GetPagedObjectsByNVC(
- int startIndex, int pageSize,
- NameValueCollection nvc, bool isAnd)
- {
- IQueryable<UserT_TractInfo> query =
- Consulting.Instance.UserT_TractInfo;
- query.Where(t => t.IsDel == 0).
- Where(t => t.IsAuditing == 1);//審核和邏輯刪除
- Expression condition = null;
- ParameterExpression param = Expression.
- Parameter(typeof(UserT_TractInfo), "c");
- int propertyCount = 0;
- foreach (string key in nvc)
- {
- Expression right = Expression.Constant(nvc[key]);//鍵
- string keyProperty = key;//屬性
- if (typeof(UserT_TractInfo).GetProperty(keyProperty) != null)
- //當對象存在此屬性時(因為鍵值對可能還有很多其他的參數,例如page)
- {
- Expression left = Expression.Property(param,
- typeof(UserT_TractInfo).GetProperty(keyProperty));//建立屬性
- Expression filter = Expression.Equal(left, right);//過濾器
- if (condition == null)
- {
- condition = filter;
- }
- else
- {
- if (isAnd)
- {
- condition = Expression.And(condition, filter);
- }
- else
- {
- condition = Expression.Or(condition, filter);
- }
- }
- propertyCount++;
- }
- }
- //以上foreach組合了各個有效的鍵值對對應的conditionExpression,
- //復合查詢最重要的組合工作就這么完了
- if (propertyCount > 0)
- {
- Expression pred = Expression.Lambda(condition, param);
- MethodCallExpression whereCallExpression =
- Expression.Call(typeof(Queryable), "Where",
- new Type[] { typeof(UserT_TractInfo) },
- Expression.Constant(query), pred);
- return Consulting.Instance.UserT_TractInfo.AsQueryable().
- Provider.CreateQuery<UserT_TractInfo>(whereCallExpression).
- OrderByDescending(t => t.ID).Skip(startIndex - 1).
- Take(pageSize).ToList();//查詢出結果
- }
- else
- {
- return Consulting.Instance.UserT_TractInfo.
- OrderByDescending(t => t.ID).Skip(startIndex - 1).
- Take(pageSize).ToList();
- //如果沒有有效鍵值對,則返回全部結果
- }
- }
搞了半天本來很興奮的,之后才知道Lambda表達式是寫不出.Contains()的,我的心瓦涼瓦涼的。
LINQ模糊查詢實現階段二:
雖然李永京的文章沒給我多少幫助,但它后面有個回復很有價值:“用微軟提供的System.Linq.Dynamic方便點。”很快找到了對應例子和Dynamic.cs,也找到了《Linq to SQL Dynamic 動態查詢》,有更細致的例子,可惜Dynamic.cs也是不能使用like的,恨啊!
- return Consulting.Instance.UserT_TractInfo.Where(
- "b_number == @0","P(2007)031").OrderByDescending(t => t.ID).
- Skip(startIndex - 1).Take(pageSize).ToList();
代碼很容易,但沒什么用:(
LINQ模糊查詢實現階段三:
中文的實在是找不到了,在MS的官方BBS上找到了個鏈接,非常有用!《dynamic linq queries / dynamic where clause (part 2) 》,這個老外擴展了Dynamic.cs,寫了個PredicateExtensions類,雖然不知道他是怎么想出來的,但確實有效!
這里放出核心代碼,很容易看懂,簡單就是美!
- searchPredicate = PredicateExtensions.
- True<UserT_TractInfo>();
- foreach (string key in nvcParam)
- {
- string condition = string.Empty;
- switch (key)
- {
- case "b_number":
- condition = nvcParam[key];
- searchPredicate = searchPredicate.And(u =>
- u.B_number.Contains(condition));
- break;
- case "b_address":
- condition = nvcParam[key];
- searchPredicate = searchPredicate.And(u =>
- u.B_address.Contains(condition));
- break;
- case "b_canton":
- condition = nvcParam[key];
- searchPredicate = searchPredicate.And(u =>
- u.B_canton.Contains(condition));
- break;
- case "a_status":
- condition = nvcParam[key];
- searchPredicate = searchPredicate.And(u =>
- u.A_status.ToString().Contains(condition));
- break;
- case "b_area":
- condition = nvcParam[key];
- searchPredicate = searchPredicate.And(u =>
- u.B_area.Contains(condition));
- break;
- case "c_clinchdate":
- condition = nvcParam[key];
- searchPredicate = searchPredicate.And(u =>
- u.C_clinchdate.Contains(condition));
- break;
- default:
- break;
- }
- }
- return Consulting.Instance.UserT_TractInfo.
- Where(searchPredicate).OrderByDescending(t => t.ID).
- Skip(startIndex - 1).Take(pageSize).ToList();
下面是我寫了注釋后的PredicateExtensions,我說不清楚構造函數的True和False具體是怎么起作用的,但結果就是我的注釋那樣,在復合查詢寫條件時很重要(不過目前全寫AND就完成復合查詢了,我還沒搞多關鍵詞OR的那種):
- /// <summary>
- /// 構造函數使用True時:單個AND有效,多個AND有效;
- ///單個OR無效,多個OR無效;混合時寫在AND后的OR有效
- /// 構造函數使用False時:單個AND無效,多個AND無效;
- ///單個OR有效,多個OR有效;混合時寫在OR后面的AND有效
- /// </summary>
- public static class PredicateExtensions
- {
- 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>> expression1,
- Expression<Func<T, bool>> expression2)
- {
- var invokedExpression = Expression.Invoke(
- expression2, expression1.Parameters.Cast<Expression>());
- return Expression.Lambda<Func<T, bool>>(
- Expression.Or(expression1.Body,
- invokedExpression),
- expression1.Parameters);
- }
- public static Expression<Func<T, bool>> And<T>(
- this Expression<Func<T, bool>> expression1,
- Expression<Func<T, bool>> expression2)
- {
- var invokedExpression =
- Expression.Invoke(expression2,
- expression1.Parameters.Cast<Expression>());
- return Expression.Lambda<Func<T, bool>>
- (Expression.And(expression1.Body, invokedExpression),
- expression1.Parameters);
- }
- }
原文來自:http://www.cnblogs.com/killuakun/archive/2008/08/03/1259389.html
LINQ模糊查詢實現復合搜索的基本內容就向你介紹到這里,希望對你了解和掌握復合搜索的LINQ模糊查詢實現有所幫助。
【編輯推薦】