static class QueryableExtensions
{
private static MethodInfo StringContainsMethod;
private static MethodInfo StringStartsWithMethod;
static QueryableExtensions()
{
Type[] singleStringParam = new[] { typeof(string) };
StringContainsMethod = typeof(string).GetMethod("Contains", singleStringParam);
StringStartsWithMethod = typeof(string).GetMethod("StartsWith", singleStringParam);
}
public static IQueryable<T> AppendTextFilter<T>(this IQueryable<T> queryable, Expression<Func<T, string>> memberSelector, string condition, string value)
{
Expression expression = null;
switch (condition)
{
case "StartsWith":
expression = Expression.Call(memberSelector.Body, StringStartsWithMethod, Expression.Constant(value));
break;
case "Equals":
expression = Expression.Equal(memberSelector.Body, Expression.Constant(value));
break;
case "Contains":
expression = Expression.Call(memberSelector.Body, StringContainsMethod, Expression.Constant(value));
break;
default:
throw new NotSupportedException(string.Format("'{0}' is not a supported condition", condition));
}
var lambda = Expression.Lambda<Func<T, bool>>(expression, memberSelector.Parameters);
return queryable.Where(lambda);
}
}
When i search on google,I get above class.Well,it really help me a lot,But it still can’t meet my need.
The problem is that it can only process field of the type “string”. As you seen in the above block code ,the method can only process with T,string .
How I can process any type i want within a single method?
well, the idea would be to replace string by a generic type, this way.
But with your sample, this doesn’t make much sense, as
StartsWith, for example, can just be applied ifTValuetype isstring…