Creating an expression tree for string-concatinating two objects

.net c# expression-trees lambda


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.Callof String.Concat won't work this way, because of invalid parameter-count. So I think I need something like:

  • create a List<string>-variable-expression
  • add both values to the list
  • use String.Concatwith 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?

1/19/2017 1:24:27 PM

Accepted Answer

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) });
1/19/2017 1:20:21 PM

Related Questions

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow