2011-04-23 166 views
11

我正在創建一個使用Lambda/LINQ for dynamic where和orderby的概念證明。以下代碼適用於where表達式,但我無法弄清楚如何通過表達式創建順序。對於這個例子,如果可能的話,我想保持簡單;我寧願不編寫修改表達式樹的代碼。爲LINQ/Lambda創建OrderBy表達式

void Main() 
{ 
    DateTime productSince = DateTime.UtcNow.Subtract(new TimeSpan(1,30,0)); 
    Expression<Func<Products, bool>> filter = d => d.CreatedDate > productSince && d.Price < 100 ;  
    List<Products> products = GetProducts(filter, Products); 
    Console.WriteLine(products); 
} 

private static List<Products> GetProducts(Expression<Func<Products, bool>> filter, Table<Products> Products) 
{ 

    var products = Products.Where(filter); 
    return products.ToList(); 
} 

我想要的是類似於以下,但不能找出代碼來創建按順序的順序。

void Main() 
{ 
    DateTime productSince = DateTime.UtcNow.Subtract(new TimeSpan(1,30,0)); 
    Expression<Func<Products, bool>> filter = d => d.CreatedDate > productSince && d.Price < 100 ; 
    Expression<Func<Products, ????>> orderBy = d => ??????; 

    List<Products> products = GetProducts(filter, orderBy, Products); 
    Console.WriteLine(products); 
} 

private static List<Products> GetProducts(Expression<Func<Products, bool>> filter, 
       Expression<Func<Products, ???>> orderBy, Table<Products> Products) 
{ 

    var products = Products.Where(filter).OrderBy(orderBy); 
    return products.ToList(); 
} 

如果您想知道,我正在使用LinqPad進行此類概念驗證。

回答

17
private static List<Products> GetProducts<TOrderBy>(Expression<Func<Products, bool>> filter, 
       Expression<Func<Products, TOrderBy>> orderBy, Table<Products> Products) 
{ 

    var products = Products.Where(filter).OrderBy(orderBy); 
    return products.ToList(); 
} 

如果你看的OrderBy擴展方法它接受Expression<Func<T, TOrderBy>>,因爲表達可導致任何類型取決於

.OrderBy(x => x.ID) // <T, int> 
.OrderBy(x => x.Name) // <T, string> 

所以,爲此您的包裝方法需要能夠接受泛型類型傳遞在

+0

感謝您的回答,但我如何參考TOrderBy? – 2011-04-23 19:10:51

+0

你不這樣做,它被orderBy參數使用。 'Expression > orderBy' – 2011-04-23 19:12:40

+1

爲了幫助他人。要創建orderBy表達式,可以使用'Expression > orderBy = d => d.Price;'。價格是十進制類型。在前面的代碼中,小數可以是任何類型,例如DateTime,string或int。此類型需要匹配從expresion返回的類型。如果使用DateTime,則lambda表達式應該是d.CreatedDate之類的東西。 – 2011-04-23 19:26:52

12

你正在尋找的是:

Expression<Func<Products, dynamic>>; 

嘗試創建一個結構/類來同時擁有Expression和如果它是升序或降序。