Could you help please,
I want to build lamda for filtering list of objects. I want to have builder that will accept list of fields and values and return lambda to use later to filter the list.
I've done the following:
public class SurveyListFilterBuilder
{
public static Func<SurveysQueryResultItem, bool> Build(string[] searchField, string[] searchFieldValue, LogicalOperation operation)
{
Expression resultExpression = Expression.Constant(true);
for (var i = 0; i < searchField.Length; i++)
{
var field = searchField[i];
var fieldFilterExpression = GetFieldFilterExpression(field, searchFieldValue[i]);
if (operation == LogicalOperation.And)
resultExpression = Expression.And(resultExpression, fieldFilterExpression);
else if (operation == LogicalOperation.Or)
resultExpression = Expression.And(resultExpression, fieldFilterExpression);
}
return Expression.Lambda<Func<SurveysQueryResultItem, bool>>(resultExpression).Compile();
}
private static Expression<Func<MyClass, bool>> GetFieldFilterExpression(string field, string fieldValue)
{
switch (field)
{
case "name":
return x => x.Name.Contains(fieldValue);
case "description":
return x => x.Name.Contains(fieldValue);
default:
throw new NotSupportedException();
}
}
}
But it doesn't work because it seems I apply ADD operator bool expression and expression of Func:
The binary operator And is not defined for the types 'System.Boolean' and 'System.Func`2[ConsoleApp1.MyClass,System.Boolean]'.'
The question is how can I fix it and achieve correct result?