在字符串数组中查找Any方法

本文关键字:Any 方法 查找 字符串 数组 | 更新日期: 2023-09-27 18:12:43

给定

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表达式树。

在字符串数组中查找Any方法

您也可以进行

// 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"));

也许是这样的?

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") });