您可以查看谓词生成器,或构建自己的表达式(这里是一个带有静态扩展方法的可能解决方案 on IQueryable<QuestionsMetadatas>
)
public static IQueryable<QuestionsMetaDatas> FilterText(this IQueryable<QuestionsMetaDatas> queryable, IEnumerable<string> keywords)
{
var entityType = typeof(QuestionsMetaDatas);
var parameter = Expression.Parameter(entityType, "a");
var containsMethod = typeof(string).GetMethod("Contains"
, new[] { typeof(string) });
var propertyExpression = Expression.Property(parameter, "Text");
Expression body = Expression.Constant(false);
foreach (var keyword in keywords)
{
var innerExpression = Expression.Call(propertyExpression, containsMethod, Expression.Constant(keyword));
body = Expression.OrElse(body, innerExpression);
}
var lambda = Expression.Lambda<Func<QuestionsMetaDatas, bool>>(body, new[] { parameter });
return queryable.Where(lambda);
}
哪里lambda
看起来像这样:
a => ((False OrElse a.Text.Contains("firstKeyWord")) OrElse a.Text.Contains("secondKeyWord"))
和用法是
var query = context.QuestionsMetaDatas.AsQueryable();
var keywords=new List<string>(){ "Test1","Test2" };
query = query.FilterText(keywords);
或更短
var query = context.QuestionsMetaDatas.AsQueryable().FilterText(new[]{"Test1", "Test2"});