user1455879
user1455879

Reputation: 141

how to create dynamic query using Lambda expression

I am using search functionality in this i have threee fileds

Example:- Name, State, age

when i select the name and search it should display the related record,

and when i select Name, State and search i should display the record which the both selected options are included in the record,

if the record is not having any of the selected option then it should not display the record,

so for this i should use dynamic query using lambda expression

so please send me any example to this.

Upvotes: 1

Views: 738

Answers (1)

Pranay Rana
Pranay Rana

Reputation: 176896

You can use like this , Make use of Predicate Builder

I have same application you can check here : Dynamic query with Linq

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

    if(!string.IsNullOrEmpty(txtAddress.Text))
        predicate = predicate.And(e1 => e1.Address.Contains(txtAddress.Text));
    if (!string.IsNullOrEmpty(txtEmpId.Text))
        predicate = predicate.And(e1 => e1.Id == Convert.ToInt32(txtEmpId.Text));
    if (!string.IsNullOrEmpty(txtDesc.Text))
        predicate = predicate.And(e1 => e1.Desc.Contains(txtDesc.Text));
    if (!string.IsNullOrEmpty(txtName.Text))
        predicate = predicate.And(e1 => e1.Name.Contains(txtName.Text));

    EmployeeDataContext edb= new EmployeeDataContext();
    var emp = edb.Employees.Where(predicate);
    grdEmployee.DataSource = emp.ToList();
    grdEmployee.DataBind();

Dynamically Composing Expression Predicates

Upvotes: 1

Related Questions