从具有多个条件的数据表中选择

时间:2016-08-13 07:17:12

标签: c# asp.net asp.net-mvc

我有一个数据表,有两列(源,目标),我想从条件中选择它 我有两个过滤器(源,目的地)

如果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();


}

我的问题是,对于这种情况,更好的方法是什么? 因为任何过滤器都可以随时添加 谢谢你的帮助

1 个答案:

答案 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 + "%'";
}