Alex Rivera | Logout

Joining multiple where clauses in LINQ as OR instead of AND

Asked 2010-09-28T03:48:09.560
17

Is there anyway to join LINQ where clauses as OR ?

var ints = new [] { 1, 3, 5, 7 };

var query = from i in ints select i;

query = query.Where (q => q == 3);

query = query..Where (q => q == 7);

What I want is the ability to dynamically add where clauses but make them use OR instead of AND

Edit
Report

2 Answers

3

How about something like this?

var query = from i in ints where CheckConditions(i) select i;

public bool CheckConditions(int i)
{
    var conditions = WhereConditions; //an IEnumerable<Func<int, bool>> of  dynamically added conditions
    foreach (var condition in conditions)
    {
        if (condition(i)) return true;
    }
    return false;
}

You can probably expand this to be a bit cleverer but that's sort of how I'd do it.

EDIT: Sorry the first example was an AND, have changed it now to be an OR. So the first time it encounters a passing condition it returns true.

answered 2010-09-28T04:06:27.740
-3

try this

var ints = new [] { 1, 3, 5, 7 };

var query = ints.select(X=>X).where(X=>X==3||X==7);

answered 2010-09-28T03:55:48.410

Your Answer