MVC3 where 子句中的动态检查数

MVC3 dynamic number of checks in where clause

在我看来,我有多个 select 和一些服务器名称列表。服务器的数量将是动态的并且变化非常频繁。

<select name="servers" class="selectpicker" multiple data-live-search="true">
  <optgroup label="Prod5">
    <option>VS12</option>
    <option>...</option>                
  </optgroup>
  <optgroup label="UAT6">
    <option>VS13</option>
    <option>...</option>                        
  </optgroup>
</select>

在控制器中,我需要根据 KPIKey 的一些静态数字和服务器名称 (kpi.KPIserver) 过滤数据库,这些名称将由用户从多个 select 中选择。如何向下面的 where 子句添加动态数量的 KPIserver 检查,例如

其中 kpi.KPIkey == "CPU usage" || kpi.KPIkey == "I/O operations" && kpi.KPIserver == "VS12" || kpi.KPIserver == "VS13" || kpi.KPIserver == ...

[HttpPost]
    public ActionResult Index(FormCollection fs)
    {

        IEnumerable<kpi_master> allKPI = null;

        try
        {               
            allKPI = from kpi in db.kpi_masters
                     where kpi.KPIkey == "CPU usage" || kpi.KPIkey == "I/O operations"                                                  
                     select kpi;
        }
        catch (Exception e) { log.Error("KPI POST error: " + e.Message); }

        return View(allKPI);

    }

如果您有一定数量的要检查的字段,那就很容易了。

var keys = new List<string>()  { "CPU usage", "I/O operations" };
var servers = new List<string>() { "VS13", "SERVERX" };

.....

allKPI = allKPI = from kpi in db.kpi_masters
                  where keys.Contains(kpi.KPIkey) || servers.Contains(kpi.KPIserver)
                  select kpi;

如果子句数量是动态的,请改用 linq 扩展方法。 然后像

var result = collection. Where (o => contional clause 1);
foreach (var extraclause in dynamicClauses)
{
    result = result.Where (o => extraclause (o));
}

所以可以动态添加子句,查询只会在枚举集合(结果)时执行。如果你想立即强制执行加一个

var final = result.ToArray ();