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
If you want to build it dynamically, you could use the PredicateBuilder
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)));
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>
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With