JSon.Mvc JSon.Mvc - 3 months ago 15
ASP.NET (C#) Question

select from datatable with multiple condition

I have a datatable,that have two column (source,destination) and I want select from it with condition
I have two filter (source,destination)

If soruce is not null select from it where like soruce

if destination is not null select from it where like destination
if both are not null select from it where like source and destination

This is my code

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


}


my question is ,what's the beter way for this scenario ?
because it's possible any filter add after time
thank you for your help

Answer

Ok, this is your clear code. you can continue with this trend

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();
}

so basically you can add 3 line with the new parameter

if (model.newparam!= null)
{
    if(query!=string.Empty)
        query+=" and ";
     query +="newparam like '" + model.newparam + "%'";
}
Comments