Last active
March 7, 2017 07:41
-
-
Save karthikeyanVK/b9aa9fa302446e344d39f7f30192a2ab to your computer and use it in GitHub Desktop.
IQueryableExtension snippet for Effective c# blog.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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