2012-05-08 49 views
3

我有兩個IQueryables的:執行或兩個LINQ IQueryables

public static IQueryable<Counterparty> SearchByCode(this IQueryable<Counterparty> queryable, string searchQuery) 
    { 
     return queryable.Where(x => x.Code.StartsWith(searchQuery.ToUpper())); 
    } 

    public static IQueryable<Counterparty> SearchByName(this IQueryable<Counterparty> queryable, string searchQuery) 
    { 
     return queryable.Where(x => x.Name.ToLower().Contains(searchQuery.ToLower())); 
    } 

我想創建另一個IQueryable的它結合了兩個查詢作爲或EG

public static IQueryable<Counterparty> SearchByCodeOrName(this IQueryable<Counterparty> queryable, string searchQuery) 
    { 
     // return SearchByName(searchQuery) OR SearchByCode(searchQuery) 
    } 

我寧願避免重複的代碼,所以我想重複使用現有的查詢語句,而不是重寫一個新的lambda表達式,如Where(x=> x.Code.StartsWith.... || x.Name.Contains.....)

回答

1

取決於你希望能夠重用什麼樣的代碼,這可能是做這件事,你不重複的查詢條件的內部運作的另一種方式:

private static Func<Counterparty, string, bool> CodeStartsWith = (x, searchQuery) => x.Code.StartsWith(searchQuery.ToUpper()); 

    private static Func<Counterparty, string, bool> NameContains = (x, searchQuery) => x.Name.Contains(searchQuery.ToLower()); 

    public static IQueryable<Counterparty> SearchByCode(this IQueryable<Counterparty> queryable, string searchQuery) 
    { 
     return queryable.Where(x => CodeStartsWith(x, searchQuery)); 
    } 

    public static IQueryable<Counterparty> SearchByName(this IQueryable<Counterparty> queryable, string searchQuery) 
    { 
     return queryable.Where(x => NameContains(x, searchQuery)); 
    } 

    public static IQueryable<Counterparty> SearchByCodeOrName(this IQueryable<Counterparty> queryable, string searchQuery) 
    { 
     return queryable.Where(x => NameContains(x, searchQuery) || CodeStartsWith(x, searchQuery)); 
    } 
+1

這實際上是我自己提出的方法!好答案! – reach4thelasers

+0

@ reach4thelasers:你應該看看[Albaharis的PredicateBuilder](http://www.albahari.com/nutshell/predicatebuilder.aspx)和[這個EF/ORM友好版本](http://petemontgomery.wordpress。 com/2011/02/10/a-universal-predicatebuilder /)和[後者的鏈接解釋](http://blogs.msdn.com/b/meek/archive/2008/05/02/linq-to-entities -combining-predicates.aspx)關於如何使用表達式解決問題。 :-) –

5

您可以將兩者的結果聯合起來

public static IQueryable<Counterparty> SearchByCodeOrName(this IQueryable<Counterparty> queryable, string searchQuery) 
{ 
    return SearchByName(searchQuery).Union(SearchByCode(searchQuery)) 
} 
+0

絕對是最新的方法,但我不知道這是否會導致兩個往返實體框架中的數據庫或不... – reach4thelasers