在我的视图中,我有一个带有一些服务器名称列表的多选。服务器数量将是动态的并且经常变化。
<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)过滤db,用户将从多个select中选择。如何在下面的where子句中添加动态数量的KPIserver检查,例如
其中kpi.KPIkey ==&#34; CPU使用率&#34; || kpi.KPIkey ==&#34; I / O操作&#34; &安培;&安培; kpi.KPIserver ==&#34; VS12&#34; || kpi.KPIserver ==&#34; VS13&#34; || 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);
}
答案 0 :(得分:1)
如果您正在检查一定数量的字段,那么这很容易。
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;
答案 1 :(得分:0)
如果子句数是动态的,则使用linq扩展方法。 然后像
var result = collection. Where (o => contional clause 1);
foreach (var extraclause in dynamicClauses)
{
result = result.Where (o => extraclause (o));
}
因此,您可以动态添加子句,并且只有在枚举集合(结果)时才会执行查询。如果要强制执行,请立即添加
var final = result.ToArray ();