根据书籍构建LINQ查询

时间:2009-07-17 14:46:31

标签: c# .net 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 个答案:

答案 0 :(得分: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);

答案 1 :(得分: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类型,以便更轻松地构建列表...

答案 2 :(得分: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;
}