2013-04-10 38 views
5

我需要寫一些像這樣的通用搜索方法:C#泛型LINQ查詢

public List<T> Search<T>(SearchParamsBase searchParams) 
{ 
    using (var context = new TestEntities()) 
    { 
     var dataType = TypeMap.Get(typeof (T)); 
     var dataSet = context.Set(dataType); 

     var searchQuery = CreateQuery((IEnumerable<object>) dataSet), searchParams) 

     return searchQuery.ToList() 
    } 
} 

,我有一個功能CreateQuery()應該過濾IEnumerable對象。 這個函數對於所有類都是不同的。例如:

CreateQuery(IEnumerable<object> collection, SearchParamsBase searchParams) 
{ 
    var search = (SomeSearchImplementation)searchParams; 
    // filter 
    collection = collection.Where(x => x.Name == search.Name); 
    // select page 
    collection = collection.Skip(search.Page * search.CountPerPage); 
    collection = collection.Take(search.CountPerPage); 
    // order by and so on 
    // ... 
    return collection; 
} 

我該如何正確實現這個想法?

回答

7

你基本上想要做的是動態地構造一個LINQ查詢。爲此,您需要在運行時修改/構建表達式樹。如果你不熟悉表達式樹和Expression<T>型我推薦這篇文章和「又見」一節中引用的網頁:

http://msdn.microsoft.com/en-us/library/bb397951.aspx

既然你現在的基本概念,讓我們實現動態排序。下面的方法是對IQueryable<T>的擴展,這意味着它不僅適用於列表,而且適用於每個LINQ數據源,因此您也可以直接對數據庫使用它(對於分頁和排序而言,比內存操作更高效) 。該方法需要你想訂購的屬性名稱和排序方向(升序/降序):

public static IQueryable<T> OrderByDynamic<T>(this IQueryable<T> query, string sortColumn, bool descending) 
{ 
    // Dynamically creates a call like this: query.OrderBy(p => p.SortColumn) 
    var parameter = Expression.Parameter(typeof(T), "p"); 

    string command = "OrderBy"; 

    if (descending) 
    { 
     command = "OrderByDescending"; 
    } 

    Expression resultExpression = null;  

    var property = typeof(T).GetProperty(sortColumn); 
    // this is the part p.SortColumn 
    var propertyAccess = Expression.MakeMemberAccess(parameter, property); 

    // this is the part p => p.SortColumn 
    var orderByExpression = Expression.Lambda(propertyAccess, parameter); 

    // finally, call the "OrderBy"/"OrderByDescending" method with the order by lamba expression 
    resultExpression = Expression.Call(typeof(Queryable), command, new Type[] { typeof(T), property.PropertyType }, 
     query.Expression, Expression.Quote(orderByExpression)); 

    return query.Provider.CreateQuery<T>(resultExpression); 
} 

現在你可以這樣寫代碼由酒店Nameascending以訂購數據集:

dataSet.OrderByDynamic("Name", false) 

爲動態篩選創建擴展方法遵循相同的模式。如果你瞭解上面的代碼,那對你來說不會有問題。