在C#中的动态Where子句lambda表达式 [英] Dynamic Where clause lambdas in C#

查看:301
本文介绍了在C#中的动态Where子句lambda表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像这样的一个搜索表单:

I have a search form that looks like this:

形式背后的code是这样的:

The code behind the form looks like this:

@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从那里返回的选项条款。例如。如果用户选择过程无和包含,那么这个lambda看起来像

What I want to do is dynamically construct a lambda where clause from the return options. E.g. if the user selects "Process No" and "Contains" then the lambda would look like

model.DataSource = _db.InstrumentLists.Where(x => x.Process_No.Contains(SearchTerm));

或者,如果用户选择了PLC否和等于,然后在lambda看起来像

Or if the user selects "PLC No" and "Equals" then the lambda would look like

model.DataSource = _db.InstrumentLists.Where(x => x.PLC_No == SearchTerm);

我想,同时避免大的case语句或这样做,如果栈,即我不想如下:

I am trying to do this while avoiding a big case statement or an if stack, i.e. I don't want the following:

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);
...

基本上我想传递一个引用类属性,一些指定的测试类型(即包含,等于,开始等),搜索词给一个函数,或类似的规定,以及拿回predicate投入到我的Where子句。我想这个功能动态地工作,所以我不应该修改它的属性和测试类型中的每个组合。

这是可能或者是用字符串predicate参数用在哪里的唯一途径?

Is this possible or is the only way to use Where with a string predicate parameter?

修改:如果其重要的,我用EF为我的数据模型,使_db.InstrumentLists返回对象集&LT; InstrumentList&GT;

Edit: In case its important, I'm use EF for my data model so _db.InstrumentLists returns an ObjectSet<InstrumentList>.

推荐答案

你有2个选择这里:

you have 2 options here:

  • 做一个基础的开关的搜索方法,即根据用户选择的值执行不同的地方,并返回一个数据源

  • make a "switch" based search method i.e. depending on the value of user selection executes a different Where and returns a DataSource

使用<一个href="http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx"相对=nofollow>动态LINQ的并构建其中,字符串中的

编辑 - 例如动态的Linq:

EDIT - example for Dynamic Linq:

model.DataSource = _db.InstrumentLists.Where(SelectedType + " == @0", SearchTerm);

这篇关于在C#中的动态Where子句lambda表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆