我有一个数据表,有两列(源,目标),我想从条件中选择它 我有两个过滤器(源,目的地)
如果soruce不为null,请从中选择soruce
如果destination不为null,则从目的地选择
如果两者都不为null,请选择源和目标
这是我的代码
if (model.source != null&&model.destination == null)
{
var result = _filterFly.Select("source like '" + model.source + "%'");
if (result.Any()) _filterFly = result.CopyToDataTable(); else _filterFly.Clear();
}
if (model.source==null&&model.destination != null)
{
var result = _filterFly.Select("destination like '" + model.destination + "%'");
if (result.Any()) _filterFly = result.CopyToDataTable(); else _filterFly.Clear();
}
if (model.source!=null&&model.destination != null)
{
var result = _filterFly.Select("source like '" + model.source + "%'");
if (result.Any()) _filterFly = result.CopyToDataTable(); else _filterFly.Clear();
result = _filterFly.Select("destination like '" + model.destination + "%'");
if (result.Any()) _filterFly = result.CopyToDataTable(); else _filterFly.Clear();
}
我的问题是,对于这种情况,更好的方法是什么? 因为任何过滤器都可以随时添加 谢谢你的帮助
答案 0 :(得分:0)
好的,这是你明确的代码。你可以继续这种趋势
string query ="";
if (model.source != null)
query +="source like '" + model.source + "%'";
if (model.destination != null)
{
if(query!=string.Empty)
query+=" and ";
query +="destination like '" + model.destination + "%'";
}
if(query!=string.Empty)
{
var result=_filterFly.Select(query);
if (result.Any())
_filterFly = result.CopyToDataTable();
else
_filterFly.Clear();
}
所以基本上你可以用新参数
添加3行if (model.newparam!= null)
{
if(query!=string.Empty)
query+=" and ";
query +="newparam like '" + model.newparam + "%'";
}