I'm just learning about Expression
and their expression-trees to use them with IronPython (but that's irrelevant for now).
What I'm trying to do is, creating an expression tree like the following lambda:
Func<T, int, string> func = (s,t) => s + t;
My current function is this:
public static Expression<Func<T, int, string>> StringConcatSelector<T>()
{
var parameterParam = Expression.Parameter(typeof(T), "x");
var paramToString = typeof(T).GetMethods().FirstOrDefault(s=>s.Name=="ToString");
var parameter = Expression.Call(parameterParam, paramToString);
var intParameterParam = Expression.Parameter(typeof(int), "s");
var intParameterToString = typeof(int).GetMethods().FirstOrDefault(s => s.Name == "ToString");
var intParameter = Expression.Call(intParameterParam, intParameterToString);
var stringConcat = typeof(string).GetMethods().FirstOrDefault(s => s.Name == "Concat");
var result = Expression.Call(stringConcat, parameter, intParameter);
return Expression.Lambda<Func<T, int, string>>
(result, parameterParam, intParameterParam);
}
the Expression.Call
of String.Concat
won't work this way, because of invalid parameter-count.
So I think I need something like:
List<string>
-variable-expressionString.Concat
with the list-expression.Am I right?
If yes, how can I create a List-variable (or an Array), add both values to take it as parameter for my String.Concat
?
String.Concat
method has 11 (!) overloads, and you are taking a random one.
The most appropriate for your case is
public static String Concat(String str0, String str1)
which you can get by using the following Type.GetMethod
overload
public MethodInfo GetMethod(string name, Type[] types)
where the types
array represents the type of the method arguments:
var stringConcat = typeof(string).GetMethod("Concat",
new[] { typeof(string), typeof(string) });