Build a where clause for ORs (||) in LINQ at runtime?

dynamic-linq linq linq-to-sql

Question

I need to build a where clause at runtime but i need to do an OR with the where clause. Is this possible .. Let me explain..

here 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 than 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 psuedo 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.

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

Is this possible..

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

Any idea really appreciated

Thanks

1
3
2/20/2011 11:07:24 AM

Accepted Answer

var statusTexts = new List<string>(); // Add desired status texts
dataApplication.Where(item =>
        statusTexts.Any(status => item.Status == status))
3
2/20/2011 11:19:34 AM

Popular Answer

If you have this:

IEnumerable<MyType> res = from p in myquery select p;

You can define a

var conditions = new List<Func<MyType, bool>>();

conditions.Add(p => p.PropertyOne == 1);
conditions.Add(p => p.PropertyTwo == 2);

res = res.Where(p => conditions.Any(q => q(p)));

And now the trick to make Lists of Funcs of anonymous objects (and you can easily change it to "extract" the type of anonymous objects)

static List<Func<T, bool>> MakeList<T>(IEnumerable<T> elements)
{
    return new List<Func<T, bool>>();
}

You call it by passing the result of a LINQ query. So

var res = from p in elements select new { Id = p.Id, Val = p.Value };
var conditions = MakeList(res);


Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow