I am trying to create an Expression Tree for Enumerable.Any(IEnumerable, Func<T,bool>)
Actually, I have a list and need to check whether this list has at least 1 element that contains "test"
So it looks very simple:
List<string> strings = new List<string> { "element1", "element2", "element3" };
var test = strings.Any(x => x.Contains("test"));
I am trying to create an Expression Tree and GetMethod returns null, so I think I miss something
Here is a test code:
List<string> strings = new List<string> { "element1", "element2", "element3" };
var testString = "test";
ParameterExpression p = Expression.Parameter(typeof(string), "item");
Delegate predicate = Expression.Lambda(
Expression.Call(
p,
typeof(string).GetMethod("Contains", new[] { typeof(string) }),
Expression.Constant(testString)),
p).Compile();
Type predType = typeof(Func<,>).MakeGenericType(typeof(string), typeof(bool));
// Enumerable.Any<T>(IEnumerable<T>, Func<T,bool>)
System.Reflection.MethodInfo anyMethod = typeof(Enumerable).GetMethod("Any", new Type[] {typeof(IEnumerable<string>), predType});
Expression anyCall = Expression.Call(
anyMethod,
Expression.Constant(strings),
Expression.Constant(predicate));
// test
Func<bool> a = (Func<bool>) Expression.Lambda(anyCall).Compile();
Thanks!
GetMethod()method work for you to get the method info forAny()? For me, I cannot get it to work. If I can get past that, I can work out the rest.