串" src="/default/index/img?u=aHR0cHM6Ly9wMi5waXFzZWxzLmNvbS9wcmV2aWV3LzkxNy85NTMvMjU0L2FuZ2VsLXB1dHRlbi1nYXJkZW4tZmlndXJlLmpwZw==&w=245&h=&w=700"/>
问题描述:
阵列上,然后返回true:找到任何方法鉴于</p> <pre><code>string[] stringArray = { "test1", "test2", "test3" }; </code></pre> <p>串
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合作的实体,您可能希望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"));
'Any'是System.L中的扩展方法inq命名空间,这就是为什么你不能在字符串上找到它 – Charleh 2013-05-07 15:48:57
'Any()'是属于['Queryable']的静态扩展方法(http://msdn.microsoft.com/en-us/library/ system.linq.queryable.aspx)和/或['Enumerable'](http://msdn.microsoft.com/en-us/library/system.linq.enumerable.aspx)类(可能为您的目的使用“Queryable” )...但是你能否提供一些关于为什么需要'MethodInfo'的更多信息? – 2013-05-07 15:49:20
要追踪@JeremyTodd的声明:在'string []'上,它应该是'Enumerable'类的实现,但对于EF我希望它是'Queryable'。 – 2013-05-07 17:32:09