我正在尝试创建 ContainsAny 和 ContainsAll 扩展,因此我基本上可以执行以下操作
string[] words = keywords.split(' ');
from c in comments
where c.Text.ContainsAny(words)
select c
到目前为止,我已经设法做到了以下几点:
我对 ands 和 ors 有这两个扩展
public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> expr1, Expression<Func<T, bool>> expr2) {
var invokedExpr = Expression.Invoke(expr2, expr1.Parameters.Cast<Expression>());
return Expression.Lambda<Func<T, bool>>(Expression.OrElse(expr1.Body, invokedExpr), expr1.Parameters);
}
public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> expr1, Expression<Func<T, bool>> expr2) {
var invokedExpr = Expression.Invoke(expr2, expr1.Parameters.Cast<Expression>());
return Expression.Lambda<Func<T, bool>>(Expression.AndAlso(expr1.Body, invokedExpr), expr1.Parameters);
}
然后我有:
Expression<Func<Entities.Comment, bool>> predicate = c => false;
foreach (string word in query.Split(' ')) {
string w = word;
predicate = predicate.Or(c => c.Text.Contains(w));
}
q = q.Where(predicate);
现在这一切都很好,但我不确定如何将此功能提取到通用扩展中,然后我可以将其用于任何对象。
任何帮助将不胜感激