Easy way
Just use
if (comparison == ComparisonType.StartsWith) query = query.Where(e => e.StringProperty.StartsWith("SearchString")); else if ...
Hard way
If you want to do something like this, either make sure your LINQ provider can somehow learn about this new method, and how it will convert to SQL (unlikely), or prevent your method from ever reaching the LINQ provider and providing the provider understands something (hard). For example, instead of
query.Where(e => CompMethod(e.StringProperty, "SearchString", comparsionType))
you can create something like
var query = source.WhereLike(e => e.StringProperty, "SearchString", comparsionType)
with the following code
public enum ComparisonType { StartsWith, EndsWith, Contains } public static class QueryableExtensions { public static IQueryable<T> WhereLike<T>( this IQueryable<T> source, Expression<Func<T, string>> field, string value, SelectedComparisonType comparisonType) { ParameterExpression p = field.Parameters[0]; return source.Where( Expression.Lambda<Func<T, bool>>( Expression.Call( field.Body, comparisonType.ToString(), null, Expression.Constant(value)), p)); } }
You can even add additional criteria this way
var query = from e in source.WhereLike( e => e.StringProperty, "SearchString", comparsionType) where e.OtherProperty == 123 orderby e.StringProperty select e;
Very, very difficult way
It would be (technically) possible to rewrite the expression tree before the provider sees it, so you can use the query that you had in mind in the first place, but you need
- create
Where(this IQueryable<EntityType> source, Expression<Func<EntityType, bool>> predicate) to intercept Queryable.Where , CompMethod expression tree, replacing your CompMethod , wherever it is, with one of the String methods,- calling the original
Queryable.Where with a rewritten expression - and, above all, be able to follow the expansion method described above!
But this is probably too complicated for what you had in mind.