Dynamic where condition in LINQ

Shivi picture Shivi · Apr 15, 2011 · Viewed 16.7k times · Source

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...

Answer

Pranay Rana picture Pranay Rana · Apr 15, 2011

Please check out the full blog post: Dynamic query with Linq

There are two options you can use:

Dynamic LINQ library

string condition = string.Empty;
if (!string.IsNullOrEmpty(txtName.Text))
    condition = string.Format("Name.StartsWith(\"{0}\")", txtName.Text);

EmployeeDataContext edb = new EmployeeDataContext();
if(condition != string.empty)
{
  var emp = edb.Employees.Where(condition);
 ///do the task you wnat
}
else
{
 //do the task you want 
}

Predicate Builder

Predicate builder works similar to Dynamic LINQ library but it is type safe:

var predicate = PredicateBuilder.True<Employee>();

if(!string.IsNullOrEmpty(txtAddress.Text))
    predicate = predicate.And(e1 => e1.Address.Contains(txtAddress.Text));

EmployeeDataContext edb= new EmployeeDataContext();
var emp = edb.Employees.Where(predicate);

difference between above library:

  • PredicateBuilder allows to build typesafe dynamic queries.
  • Dynamic LINQ library allows to build queries with dynamic Where and OrderBy clauses specified using strings.