I'm trying to concatenate two strings together in a dynamic linq expression. The parameter I pass to the function must be a Dictionary<string, object>
. The problem is that The Expression.Add throws me an error because it doesn't know how to add strings.
What I'm trying to achieve:
x => (string)x["FirstName"] + " Something here..."
What I have:
var pe = Expression.Parameter(typeof(Dictionary<string, object>), "x");
var firstName = Expression.Call(pe, typeof(Dictionary<string, object>).GetMethod("get_Item"), Expression.Constant("FirstName"));
var prop = Expression.Convert(firstName, typeof(string));
var exp = Expression.Add(prop, Expression.Constant(" Something here..."))
Adding strings is neither one of the types that expressions handles explicitly (as it does for numeric primitives) nor going to work due to an overload of +
(since string
has no such overload), so you need to explicitly defined the method that should be called when overloading:
Expression.Add(
prop,
Expression.Constant(" Something here..."),
typeof(string).GetMethod("Concat", new []{typeof(string), typeof(string)}))
This makes the overload of string.Concat
that takes two string arguments the method used.
You could also use Expresssion.Call
but this keeps your +
intention explicit (and is what the C# compiler does when producing expressions, for that reason).
Adding and concatenating are completely different processes. When you "add" two strings together, you are concatenating them, since doing a mathematical addition on strings makes no sense.
The best way to concatenate strings is by using String.Concat
. You can use Expression.Call
to generate the method expression:
// Create the parameter expressions
var strA = Expression.Parameter(typeof(string));
var strB = Expression.Parameter(typeof(string));
// Create a method expression for String.Join
var methodInfo = typeof(string).GetMethod("Concat", new[] { typeof(string), typeof(string) });
var join = Expression.Call(methodInfo, strA, strB);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.