4

与えられた

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式ツリーを使用して動的ラムダ式ツリーを作成しています。この場合、説明フィールドに文字列が出現する文字列の配列があります。Where句に入る作業ラムダ式は次のとおりです。

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

したがって、ラムダ式の本体を作成するには、 への呼び出しが必要"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、より大きなラムダ式ツリーに入ります。

4

2 に答える 2

2

あなたもできる

// 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"));
于 2013-05-07T16:24:48.490 に答える