Need help in using PredicateBuilder
Asked Answered
M

1

6

I need to know about using PredicateBuilder. On almost every example of how to use it, they show the code as follows:

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();

What is that Employee object, the one between the greater than and less than brackets? I have racked my brains on that one. I am using Linq to SQL entities and I get compile errors when I try this myself. I think the errors are something like:

"Cannot cast from a Linq table to..."

I am a beginner. Please forgive me for asking what may be an obvious thing. Thank you.

Mohandas answered 7/11, 2012 at 0:47 Comment(1)
Those <...> are called generics, i don't know how to use linq but maby this helps: msdn.microsoft.com/en-us/library/bb546142.aspxAntilogy
C
2

As @MatsRietdijk stated in the comments section, this is generics being used. Basically, with generics you can create a method that will operate on a type/class ("employee" in this instance) that is unknown (although you can control this with the where statement).

If you were to change the employee type for some other type (e.g. customer), then the properties available in the lambda expressions would also be different, based upon whatever properties were publically exposed. For example:

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

// There is no "CustomerName" property from employee, but there is for customer objects
if (!string.IsNullOrEmpty(txtName.Text))
    predicate = predicate.And(e1 => e1.CustomerName.Contains(txtName.Text));
Coolish answered 7/11, 2012 at 4:7 Comment(1)
Thank you for the answer. I forgot that point. I'll try it. Also, thank you MatsReitdijk for the link. thanks again.Mohandas

© 2022 - 2024 — McMap. All rights reserved.