I have a scenario where I have to use a dynamic where condition in LINQ.
I want something like this:
public void test(bool flag)
{
from e in employee
where e.Field<string>("EmployeeName") == "Jhom"
If (flag == true)
{
e.Field<string>("EmployeeDepartment") == "IT"
}
select e.Field<string>("EmployeeID")
}
I know we can't use the 'If' in the middle of the Linq query but what is the solution for this?
Please help...
You can call LINQ methods explicitly and chain them conditionally.
So, if
flag
isfalse
you need all Jhoms, and ifflag
is true you need only the Jhoms in the IT departmentThis condition
satisfies that criterion (it's always true if flag is false, etc..), so the query will become:
also, this
e.Field<string>("EmployeeID")
business, smells like softcoding, might take a look into that. I guesswould be more compact and less prone to typing errors.
EDIT: This answer works for this particular scenario. If you have lots of this kinds of queries, by all means investingate the patterns proposed in the other answers.
Please check out the full blog post: Dynamic query with Linq
There are two options you can use:
Dynamic LINQ library
Predicate Builder
Predicate builder works similar to Dynamic LINQ library but it is type safe:
difference between above library:
You can chain methods :