Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use where condition

Tags:

c#

dynamic

linq

can we dynamically appened where condition on a linq query?

for example:

class Result
{
      string v1;
      string v2;
      string v3;
}

List<Result> result = (from r in results select r);


//i want to do something like the following....

if(conditionA)
{
    result = result appened (or v1 = xxx)
}
else if(conditionB)
{
    result = result appened (or v2 = xxx)
}
else if(conditionC)
{
    result = result appened (or v3 == xxx)
}

Anyone know how handle the condition in Linq????

Th

like image 824
jojo Avatar asked Feb 25 '10 00:02

jojo


4 Answers

If you want to build it dynamically, you could use the PredicateBuilder

like image 102
bkaid Avatar answered Oct 09 '22 10:10

bkaid


For an and relationship of clauses, you can easily just append the .Where() filter method, as such:

where conditionOriginal(r) and conditionDynamic(r)

as

var results = (from r in originalResults
               where originalConditions(r)
               select r);
...
if (conditionA)
    results = results.Where(r => conditionDynamic(r));

To append an 'or' type relationship, however, you'd have to union with the original result set, like so:

where conditionOriginal(r) or conditionDynamic(r)

becomes

var results = (from r in originalResults
               where conditionOriginal(r)
               select r);
...
if (conditionB)
    results = results.Union((from r in originalResults
                             where conditionDynamic(r)
                             select r));

or

if (conditionB)
    results = results.Union(originalResults.Where(conditionDynamic(r)));
like image 45
Tanzelax Avatar answered Oct 09 '22 11:10

Tanzelax


Just append the Where query operator to your query :

if(conditionA)
{
    result = result.Where(r => r.v1 == xxx);
}
else if(conditionB)
{
    result = result.Where(r => r.v2 == xxx);
}
else if(conditionC)
{
    result = result.Where(r => r.v3 == xxx);
}

Note that your results variable should be declared as IEnumerable<Result>, not List<Result>

like image 2
Thomas Levesque Avatar answered Oct 09 '22 10:10

Thomas Levesque


You can do this:

if (conditionA)
{
    result = result.Where(p => p.v1 == xxx); // Just guessing at the intent here.
}
// Repeat as necessary...

Or this:

if (conditionA)
{
    result = from r in result where p.v1 == xxx select r;
}
like image 1
Marcelo Cantos Avatar answered Oct 09 '22 11:10

Marcelo Cantos