Search code examples
c#sqllinqdynamicquery

Linq query construction based on empty parameters


I have an object like this:

public class Filters
{
    List<string> A { get; set; }
    List<string> B { get; set; }
}

I will use it as parameters of a function that will execute a query on a Database. These itens, A and B, will indicate the "where" filters.

Look at the following code:

//Filters Initialization
Filters TestFilters = new Filters();
TestFilters.A = new List<string>();
TestFilters.B = new List<string>(new string[] {"testfilter1","testfilter2"}); //WHERE B == "testfilter1" OR B == "testfilter2"

//Call of the function that executes SELECT on DB
List<Table> Result = TestFunction(TestFilter);

The function:

public static List<Table> TestFunction(Filters pParameter)
{
    ExampleDataContext dc = new ExampleDataContext(Properties.Settings.Default.ExampleConnectionString);
    List<Table> SelectResult = new List<Table>();

    if (pParameter.A.count != 0 && pParameter.B.count != 0)

        SelectResult = (from x in dc.Table
            where pParameter.A.Contains(x.A)
            where pParameter.B.Contains(x.B)
            select x).ToList();

    else if (pParameter.A.count == 0 && pParameter.B.count != 0)
    {
        SelectResult = (from x in dc.Table
            where pParameter.B.Contains(x.B)
            select x).ToList();
    }

    else if (pParameter.A.count != 0 && pParameter.B.count == 0)
    {
        SelectResult = (from x in dc.Table
            where pParameter.A.Contains(x.A)
            select x).ToList();
    }

    else if (pParameter.A.count == 0 && pParameter.B.count == 0)
    {
        SelectResult = (from x in dc.Table
            select x).ToList();
    }       

    return SelectResult;
}

Sometimes A or/and B is/are empty, then I am using "IF" structure to handle it. Maybe I could face a problem where my filter is bigger, more than 2 parameters, and it would be difficult/boring to code. My question is: It is working, but is there another way to do it, instead of using IF?


Solution

  • I have tried some of the options, but unsucessfully. Below you can find the code that worked for me:

    List<Table> SelectResult = (from x in dc.Table
                                where (pParameter.A.Count != 0 ? pParameter.A.Contains(x.A) : true)
                                where (pParameter.B.Count != 0 ? pParameter.B.Contains(x.B) : true)
                                select s).ToList();