我想我会在 String 上进行扩展,而不是在 IQueryable 上。
public static bool ContainsIfNotEmpty( this string source, string text )
{
if (string.IsNullOrEmpty(text))
{
return true; // select all elements
}
if (string.IsNullOrEmpty(source))
{
return false; // select no elements
}
return source.Contains(text); // select only matching
}
然后将其用作:
customers = MyDataContext.Customers
.Where( c => c.Email.ContainsIfNotEmpty( input ) );
请注意,这需要 LINQ to 对象。如果您需要将它与 LINQ to SQL 一起使用,那么我建议使用构建器方法构建表达式。请注意,以下内容未经测试,因为我现在无法访问 VS。您可能想查看 Andrew Peters 的博客条目以获取类似示例和/或Expression类的文档。
public static class ExpressionBuilders
{
public static Expression<Func<T,bool>> ContainsBuilder<T>( string column, string text )
{
ParameterExpression parameter = new Expression.Parameter( typeof(T), "t" );
if (string.IsNullOrEmpty(text))
{
return (Expression<Func<T,bool>>)QueryExpression.Lambda( Expression.Constant( true ), parameter );
}
MethodInfo contains = typeof(T).GetMethod("Contains");
Expression textExpression = Expression.Constant(text);
Expression containsExpression = Expression.Call(parameter,contains,textExpression);
return (Expression(Func<T,bool>))QueryExpression.Lambda( containsExpression, parameter );
}
}
用作:
var predicate = ExpressionBuilders.ContainsBuilder<Customer>( "Email", input );
customers = MyDataContext.Customers.Where( predicate );