Find any method in an array of strings

Considering

string[] stringArray = { "test1", "test2", "test3" }; 

then this returns true:

 bool doesContain = stringArray.Any(s => "testa test2 testc".Contains(s)); 

My ultimate goal is to make a linq expression tree from this. The question is, how do I get information about the "Any" method? The following do not work because it returns null.

 MethodInfo info = typeof(string[]).GetMethod("Any", BindingFlags.Static | BindingFlags.Public); 

Further explanation:

I am creating a search function. I use EF and still using linq expressions works to create a dynamic lambda expression tree. In this case, I have an array of lines from which any line should appear in the description field. A working lambda expression that is part of the Where clause:

 c => stringArray.Any(s => c.Description.Contains(s)); 

So, to create the body of a lambda expression, I need a call to "Any" .

End Code:

Thanks to the I4V answer, creating this part of the expression tree now looks like this (and works):

 //stringArray.Any(s => c.Description.Contains(s)); if (!String.IsNullOrEmpty(example.Description)) { string[] stringArray = example.Description.Split(' '); //split on spaces ParameterExpression stringExpression = Expression.Parameter(typeof(string), "s"); Expression[] argumentArray = new Expression[] { stringExpression }; Expression containsExpression = Expression.Call( Expression.Property(parameterExpression, "Description"), typeof(string).GetMethod("Contains"), argumentArray); Expression lambda = Expression.Lambda(containsExpression, stringExpression); Expression descriptionExpression = Expression.Call( null, typeof(Enumerable) .GetMethods() .Where(m => m.Name == "Any") .First(m => m.GetParameters().Count() == 2) .MakeGenericMethod(typeof(string)), Expression.Constant(stringArray), lambda);} 

And then descriptionExpression goes into the larger lambda expression tree.

+4
source share
2 answers

Maybe something like this?

 var mi = typeof(Enumerable) .GetMethods() .Where(m => m.Name == "Any") .First(m => m.GetParameters().Count() == 2) .MakeGenericMethod(typeof(string)); 

And you can call it like:

 var result = mi.Invoke(null, new object[] { new string[] { "a", "b" }, (Func<string, bool>)(x => x == "a") }); 
+1
source

You can also do

 // You cannot assign method group to an implicitly-typed local variable, // but since you know you want to operate on strings, you can fill that in here: Func<IEnumerable<string>, Func<string,bool>, bool> mi = Enumerable.Any; mi.Invoke(new string[] { "a", "b" }, (Func<string,bool>)(x=>x=="a")) 

And if you are working with Linq to Entities, you may need to overload IQueryable:

 Func<IQueryable<string>, Expression<Func<string,bool>>, bool> mi = Queryable.Any; mi.Invoke(new string[] { "a", "b" }.AsQueryable(), (Expression<Func<string,bool>>)(x=>x=="b")); 
+2
source

Source: https://habr.com/ru/post/1479571/


All Articles