特定
string[] stringArray = { "test1", "test2", "test3" };
然後返回true:
bool doesContain = stringArray.Any(s => "testa test2 testc".Contains(s));
我的最終目標是製作一個linq表達式樹。問題是我如何獲得"Any"
的方法信息?以下內容不起作用,因為它返回null。
MethodInfo info = typeof(string[]).GetMethod("Any", BindingFlags.Static | BindingFlags.Public);
進一步說明:
我正在創建搜索功能。我使用EF,到目前為止使用linq表達式樹來創建動態lambda表達式樹。在這種情況下,我有一個字符串數組,任何字符串都應該出現在描述字段中。進入Where
子句的工作lambda表達式是:
c => stringArray.Any(s => c.Description.Contains(s));
所以,為了使lambda表達式的主體我需要調用"Any"
。
最終代碼:
感謝I4V的回答,創建表達式樹的這一部分現在看起來像這樣(並且有效):
//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);}
然後descriptionExpression
進入一個更大的lambda表達式樹。
也許是這樣的?
var mi = typeof(Enumerable)
.GetMethods()
.Where(m => m.Name == "Any")
.First(m => m.GetParameters().Count() == 2)
.MakeGenericMethod(typeof(string));
你可以調用它:
var result = mi.Invoke(null, new object[] { new string[] { "a", "b" },
(Func<string, bool>)(x => x == "a") });
你也可以這樣做
// 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"))
如果您正在使用Linq to Entities,您可能需要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"));