Search code examples
linqlinq-to-sqldynamic-linq

LINQ: Build a where clause at runtime to include ORs ( || )?


I need to build a where clause at runtime but I need to do an OR with the where clause. Is this possible?

Here is my code. Basically "filter" is a enum Bitwise, son hence filter could be equal to more than 1 of the following. Hence I need to build up the where clause.

If I execute the WHEREs separately then imagine if I do the Untested first, and it returns 0 records that means I can't execute a where on the Tested because its now 0 records.

I will put some pseudo-code below:

        string myWhere = "";

        if ((filter & Filters.Tested) == Filters.Tested)
        {
             if (myWhere != "" ) myWhere =myWhere + "||";
             myWhere = myWhere " Status == "Tested";

        }

        if ((filter & Filters.Untested) == Filters.Untested)
        {
             if (myWhere != "" ) myWhere =myWhere + "||";
             myWhere = myWhere " Status == "Untested";
        }

        if ((filter & Filters.Failed) == Filters.Failed)
        {
             if (myWhere != "" ) myWhere =myWhere + "||";
             myWhere = myWhere " Status == "Failed";
        }

        // dataApplications = a List of items that include Tested,Failed and Untested.

        // dataApplication.Where ( myWhere) ---  Confused here!  

Is this possible?

I don't want to include lots of "IFs" because there are lots of combinations i.e. no filter, filter= tested Only, filter = Untested and Tested ... and lots more.


Solution

  • var statusTexts = new List<string>(); // Add desired status texts
    dataApplication.Where(item =>
            statusTexts.Any(status => item.Status == status))