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

dynamic-linq linq linq-to-sql


I have to construct a where clause at runtime, but I also have to combine it with another clause. Is that even feasible. I'll explain.

Here is my code; "filter" is essentially an enum. Filter might be greater than one of the following if it is bitwise. I must thus construct the where clause.

Imagine that if I run the where statements individually and the Untested returns 0 records; this would prevent me from running a where on the Tested since there are now 0 records.

I'll provide some fake 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 it feasible.

There are several combinations, such as "no filter," "filter = tested only," "filter = untested and tested," and many more, therefore I don't want to put a lot of "IFs."

Thanks a lot for any suggestions.


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))
2/20/2011 11:19:34 AM

Popular Answer

If you own this

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

You may specify 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)));

The next step is to create lists of functions for 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>>();

The result of a LINQ query is sent when calling it. 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