我有一个如下所示的搜索表单:
表单背后的代码如下所示:
@using (Html.BeginForm())
{
@Html.ValidationSummary()
<div>
@Html.DropDownList("SelectedType", Model.TypeOptions)
@Html.DropDownList("SelectedSearch", Model.SearchOptions)
@Html.TextBoxFor(x => x.SearchTerm)
<input type="submit" value="Search" />
</div>
}
我想做的是根据返回选项动态构造一个 lambda where 子句。例如。如果用户选择“Process No”和“Contains”,那么 lambda 看起来像
model.DataSource = _db.InstrumentLists.Where(x => x.Process_No.Contains(SearchTerm));
或者如果用户选择“PLC No”和“Equals”,那么 lambda 看起来像
model.DataSource = _db.InstrumentLists.Where(x => x.PLC_No == SearchTerm);
我正在尝试这样做,同时避免使用大的 case 语句或 if 堆栈,即我不想要以下内容:
if (SelectedType == "Process No" And SelectedSearch = "Contains")
model.DataSource = _db.InstrumentLists.Where(x => x.Process_No.Contains(SearchTerm));
elseif (SelectedType == "Process No" And SelectedSearch = "Equals")
model.DataSource = _db.InstrumentLists.Where(x => x.Process_No == SearchTerm);
...
本质上,我想传递对类属性的引用、指定测试类型(即包含、等于、开始于等)的内容和对函数的搜索词,或类似的内容,以及取回一个谓词以放入我的 Where 子句中。我希望此函数动态运行,因此我不必为属性和测试类型的每种组合修改它。
这是否可能或者是将 Where 与字符串谓词参数一起使用的唯一方法?
编辑:如果它很重要,我将 EF 用于我的数据模型,所以 _db.InstrumentLists 返回 ObjectSet<InstrumentList>
.
最佳答案
这里有 2 个选项:
创建基于“切换”的搜索方法,即根据用户选择的值执行不同的 Where 并返回数据源
使用 Dynamic Linq并从字符串构造
Where
编辑 - 动态 Linq 示例:
model.DataSource = _db.InstrumentLists.Where(SelectedType + " == @0", SearchTerm);
关于c# - C# 中的动态 Where 子句 lambda,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7200245/