与えられた
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
、より大きなラムダ式ツリーに入ります。