LINQ: Create a where clause at run time to include ORs (||)?

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

here is my code ... basically "filter" is a bitwise renaming, son, so the filter can be equal to more than 1 of the following. So I need to create a where clause ...

If I execute the sections separately, than I suppose, if I do Untested first and it will return 0 records, which means that I can’t execute where on testing, because there are now 0 records.

I will put the code under the alias 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 possible.

"IFs", cobinations, .. , filter = testing Only, filter = Untested and Tested...

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

:

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

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

Funcs ( "" )

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

, LINQ.

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

Use a HashSet <> for statuses, then there .Containswill be O (1) instead of the usual O (n) for List <>:

var statuses = new HashSet<string>() {"a", "b", "c"};
var list = new[] {
    new {   Id = 1, status = "a"},
    new {   Id = 2, status = "b"},
    new {   Id = 3, status = "z"}
};

var filtered = list.Where(l => statuses.Contains(s => l.status == s));
0
source

Source: https://habr.com/ru/post/1793368/


All Articles