I am wanting to implement the following method
public static class Filters
{
public static Expression<Func<T,bool>> ContainsText<T>(
string text, params Expression<Func<T,string>>[] fields)
{
//..
}
}
so that if I wanted to (for example) find anyone whose name contains "Mark" or whose dad's name contains "Mark", I can do something like this:
var textFilter = Filters.ContainsText<Individual>("Mark", i=>i.FirstName, i=>i.LastName, i=>i.Father.FirstName, i => i.Father.LastName);
var searchResults = _context.Individuals.Where(textFilter).ToList();
My end goal is to be able to create a ContainsTextSpecification
to simplify text-based filtering that I can use like so:
var textSpec = new ContainsTextSpecification<Individual>(i=>i.FirstName, i=> i.LastName, i=>i.DepartmentName, i=>i.SSN, i=>i.BadgeNumber);
textSpec.Text = FormValues["filter"];
var results = individuals.Find(textSpec);
I found something that gets me close to what I want here, but I want to be able to specify the fields I want to filter by using a Func<T,string>
rather than just the name of the field. (edit: I want to be able to specify the -values- that will be checked, not the name of the fields)
static Expression<Func<T, bool>> GetExpression<T>(string propertyName, string propertyValue)
{
var parameterExp = Expression.Parameter(typeof(T), "type");
var propertyExp = Expression.Property(parameterExp, propertyName);
MethodInfo method = typeof(string).GetMethod("Contains", new[] { typeof(string) });
var someValue = Expression.Constant(propertyValue, typeof(string));
var containsMethodExp = Expression.Call(propertyExp, method, someValue);
return Expression.Lambda<Func<T, bool>>(containsMethodExp, parameterExp);
}
var results = individualRepo.Get(textSpec);