2009-07-17 56 views
1

LINQ查詢(對於這個問題的標題是不是最好的,但我不能確定是怎麼回事字吧!)構建基於布爾變量

我正在其中包含一個搜索表單上值清單。基本上,檢查項目意味着'在搜索中包含此類型'。事情是這樣的:

Search for item: __________ 
Search in: 
     [ ] Fresh Foods 
     [ ] Frozen Foods 
     [ ] Beverages 
     [ ] Deli Counter 

我有一個對象來表示此搜索:

class FoodSearchCriteria{ 
    public string SearchString {get;set;} 
    public bool SearchFreshFoods {get;set;} 
    public bool SearchFrozenFoods {get;set;} 
    public bool SearchBeverages {get;set;} 
    public bool SearchDeliCounter {get;set;} 
} 

我能想到這樣ATM的唯一方法是這樣的:

public IList<FoodItem> FindFoodItems(FoodSearchCriteria criteria) 
// in reality, this is a fuzzy search not an exact match 
var matches = _DB.FoodItems.Where(x => x.FoodTitle == SearchString); 

var inCategories = new List<FoodItem>(); 

if (criteria.SearchFreshFoods) 
    inCategories.Add(matches.Where(x => x.Type == 'Fresh Foods')); 
if (criteria.SearchFrozenFoods) 
    inCategories.Add(matches.Where(x => x.Type == 'Frozen Foods')); 
//etc etc 

return inCategories; 
} 

這種感覺就像我的代碼味道一樣,接近它的更好方法是什麼?

回答

3

你試過:

List<string> types = new List<string>(); 

if (criteria.SearchFreshFoods) { types.Add("Fresh Foods"); } 
if (criteria.SearchFrozenFoods) { types.Add("Frozen Foods"); } 
if (criteria.SearchBeverages) { types.Add("Beverages"); } 
if (criteria.SearchDeliCounter) { types.Add("Deli Counter"); } 

return _DB.FoodItems.Where(x => x.FoodTitle == SearchString && 
           types.Contains(x.Type)); 

這意味着只有一個SQL查詢,這是很方便的。

你當然可以重構FoodSearchCriteria類型,使其更容易,雖然建立列表...

5

看看PredicateBuilder

PredicateBuilder predicate = PredicateBuilder.False<FoodItem>(); 
if (criteria.SearchFreshFoods) 
{ 
    predicate = predicate.Or(x => x.Type == 'Fresh Foods'); 
} 
if (criteria.SearchFrozenFoods) 
{ 
    predicate = predicate.Or(x => x.Type == 'Frozen Foods')); 
} 
... 

_DB.FoodItems.Where(predicate); 
+0

看起來不完美。 pb ==謂詞? – Dykam 2009-07-17 15:00:34

+0

是的。道歉,現在已修復。 – 2009-07-17 15:03:48

0

我沒有時間來審查,但是這可能是一個未經考驗的解決方案。

class SearchItem 
{ 
    string Name {get; set;} 
    bool IsSelected {get; set;} 
} 

class FoodSearchCriteria 
{ 
    String searchText {get; set;} 
    IList<SearchItem> SearchItems{ get; } 
} 

public IList<FoodItem> FindFoodItems(FoodSearchCriteria criteria) 
// in reality, this is a fuzzy search not an exact match 
var matches = _DB.FoodItems.Where(x => x.FoodTitle == criteria.SearchText && 
             criteria.SearchItems.Where(si => si.IsSelected).Contains(i => i.Name == x.Type)); 

return mathces; 
}