Sli*_*k86 39
你可以链接你的where子句.您只需要一个IQueryable数据源.
var filteredData = _repository.GetAll();
//If your data source is IEnumerable, just add .AsQueryable() to make it IQueryable
if(keyWordTextBox.Text!="")
filteredData=filteredData.Where(m=>m.Keyword.Contains(keyWordTextBox.Text));
if(LocationDropDown.SelectedValue!="All")
filteredData=filteredData.Where(m=>m.Location==LocationDropDown.SelectedValue));
... etc....
Run Code Online (Sandbox Code Playgroud)
因为它是IQueryable,所以在绑定数据之前不会获取数据,因此它只会提取您需要的数据.
假设您的代码中的位置和类别由ID标识(id是组合框项目中的值属性),您可以执行类似于
function GetItems(string keyword, string consultant, int? locationId, int categoryId){
using(MyContextEntities context = new MyContextEntities()){
return context.Items.Where(item =>
(string.IsNullOrEmpty(keyword) || item.Text.Contains(keyword))
&& (string.IsNullOrEmpty(consultant) || item.Consultant.Contains(consultant))
&& (!locationId.HasValue || item.Location.Id == locationId.Value)
&& (!categoryId.HasValue || item.Category.Id == categoryId.Value)
);
}
}
Run Code Online (Sandbox Code Playgroud)
看看PredicateBuilder.它允许你做这样的事情:
IQueryable<??> SearchProducts (params string[] keywords)
{
var predicate = PredicateBuilder.True<??>();
foreach (string keyword in keywords)
{
string temp = keyword;
if(temp != String.Empty || temp != "All")
predicate = predicate.And(e => e.???.Contains (temp));
}
return dataContext.??.Where (predicate);
}
Run Code Online (Sandbox Code Playgroud)