Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating an expression tree for string-concatinating two objects

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?

like image 222
Matthias Burger Avatar asked Dec 19 '25 06:12

Matthias Burger


1 Answers

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) });
like image 82
Ivan Stoev Avatar answered Dec 21 '25 20:12

Ivan Stoev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!