Possible Duplicate:
Conditional Linq Queries
使用 Entity Framework 4.0
我有这样的搜索条件
有四个字段允许用户过滤他们的搜索。条件都是AND
。如果文本框值为 String.Empty
或下拉列表值为 All,则结果必须省略相应的过滤器。可以在存储过程中执行此操作,但我无法在 Linq2SQL/ Entity Framework 场景中完全模仿。
我的问题是,如何根据某些输入值在 Linq 中省略 IEnumerable.Where?
您可以链接您的 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....
因为它是 IQueryable,所以在您绑定(bind)它之前不会获取数据,因此它只会提取您需要的数据。