Reputation: 20078
I'm writing LINQ query that implements a keyword-style search. In other words, a query that returns rows whose Title
,Description
,Id
contains
As follows
public static IQueryable<EmployeeObject> QueryableSQL()
{
IQueryable<EmployeeObject> queryable = EmployeeRepository.GetAllEmployee();
}
public static IList<EmployeeObject> QLike(string txt)
{
IList<employeeObject> _emps = QueryableSQL().Where(x => x.Title == txt).ToList();
return _emps;
}
So far, so good. But this only handles the case where you want to match in my case Title
.
Suppose instead, I wanted to search based on the 'Descriptionor
Idshould i have to create a new method for Description? or is there a way i can create a
Tree expression`
Upvotes: 3
Views: 106
Reputation: 6304
public static IQueryable<EmployeeObject> QueryableSQL()
{
IQueryable<MediaObject> queryable = EmployeeRepository.GetAllEmployee();
}
public static IList<EmployeeObject> QLike(Expression<Func<EmployeeObject, bool>> func)
{
return QueryableSQL().Where(func).ToList();
}
You can then call this like:
QLike(t => t.Title == "MyText");
Upvotes: 3
Reputation: 7861
It sounds like you want the property you are comparing against to by dynamic, you could use reflection to do this:
public static IList<EmployeeObject> QLike(string propName, string txt)
{
PropertyInfo filterProp = typeof(EmployeeObject).GetProperty(propName);
IList<employeeObject> _emps = QueryableSQL().Where(x => filterProp.GetValue(x, null).ToString() == txt).ToList();
return _emps;
}
However the downside to this approach is that you are going to end up loading all of the objects from the database and then filtering them in your code.
If you follow the approach @gleng shows then the Ling to SQL provide will be able to do the filtering in the generated SQL statement. You do need to code the predicates upfront in that case and call the appropriate one based on what property you want to call.
Upvotes: 2
Reputation: 10896
Have you looked at Dynamic Linq? That is, of course if this text may be user provided instead of compiled.
Upvotes: 2