Skip to content

Instantly share code, notes, and snippets.

@kstrauss
Created January 11, 2016 23:56
Show Gist options
  • Save kstrauss/1af15d5c9a30d493e02e to your computer and use it in GitHub Desktop.
Save kstrauss/1af15d5c9a30d493e02e to your computer and use it in GitHub Desktop.
Example For Mark on expression tree with mulitple parameters
void Main()
{
var l = new FileModel[] { new FileModel() { Filename = "pizza is great" },
new FileModel {Filename = "MarkyMark"},
new FileModel {Filename = "JeffyJeff"}
}.AsQueryable();
var subStrings = new string[] {"is", "pizza","pizza","pizza","Mark"};
l.MultiValueContainsAny(subStrings, t=>t.Filename).Dump("Filters to");
}
public class FileModel {
public String Filename { get; set; }
public long Length { get; set;}
}
// Define other methods and classes here
public static class MyExtensions
{
public static IQueryable<T> MultiValueContainsAny<T>(this IQueryable<T> source, ICollection<string> searchKeys, Expression<Func<T, string>> fieldSelector)
{
if (source == null)
throw new ArgumentNullException("source");
if (fieldSelector == null)
throw new ArgumentNullException("fieldSelector");
if (searchKeys == null || searchKeys.Count == 0)
return source;
MethodInfo containsMethod = typeof(string).GetMethod("Contains", new Type[] { typeof(string) });
Expression expression = null;
foreach (var searchKeyPart in searchKeys)
{
Tuple<string> tmp = new Tuple<string>(searchKeyPart);
Expression searchKeyExpression = Expression.Property(Expression.Constant(tmp), tmp.GetType().GetProperty("Item1"));
Expression callContainsMethod = Expression.Call(fieldSelector.Body, containsMethod, searchKeyExpression);
if (expression == null)
expression = callContainsMethod;
else
expression = Expression.OrElse(expression, callContainsMethod);
}
return source.Where(Expression.Lambda<Func<T, bool>>(expression, fieldSelector.Parameters));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment