Skip to content

Instantly share code, notes, and snippets.

@karthikeyanVK
Last active March 7, 2017 07:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save karthikeyanVK/b9aa9fa302446e344d39f7f30192a2ab to your computer and use it in GitHub Desktop.
Save karthikeyanVK/b9aa9fa302446e344d39f7f30192a2ab to your computer and use it in GitHub Desktop.
IQueryableExtension snippet for Effective c# blog.
public static IQueryable<T> StartsWith<T>(this IQueryable<T> source, Expression<Func<T, string>> stringProperty,
string searchTerm)
{
if (string.IsNullOrEmpty(searchTerm))
{
return source;
}
var searchTermExpression = Expression.Constant(searchTerm);
//Note Below instead of GetMethod("Contains") have used GetMethod(nameof(string.Contains))
var startWithExpression = Expression.Call(stringProperty.Body,
typeof(string).GetMethod(nameof(string.StartsWith),
new[] { typeof(string) }), searchTermExpression);
var methodCallExpression = Expression.Call(typeof(Queryable), "Where", new Type[] { source.ElementType },
source.Expression,
Expression.Lambda<Func<T, bool>>(startWithExpression, stringProperty.Parameters));
return source.Provider.CreateQuery<T>(methodCallExpression);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment