生成可以将两个字符串连接在一起的C#表达式

生成可以将两个字符串连接在一起的C#表达式,c#,linq,lambda,asp.net-core,C#,Linq,Lambda,Asp.net Core,我试图在动态linq表达式中将两个字符串连接在一起。传递给函数的参数必须是字典。问题是表达式.Add抛出了一个错误,因为它不知道如何添加字符串 我正在努力实现的目标: x => (string)x["FirstName"] + " Something here..." 我所拥有的: var pe = Expression.Parameter(typeof(Dictionary<string, object>), "x"); var firstName = Expression

我试图在动态linq表达式中将两个字符串连接在一起。传递给函数的参数必须是
字典
。问题是表达式.Add抛出了一个错误,因为它不知道如何添加字符串

我正在努力实现的目标:

x => (string)x["FirstName"] + " Something here..."
我所拥有的:

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..."))
var pe=Expression.Parameter(typeof(Dictionary),“x”);
var firstName=Expression.Call(pe,typeof(Dictionary).GetMethod(“get_Item”)、Expression.Constant(“firstName”);
var prop=Expression.Convert(firstName,typeof(string));
var exp=Expression.Add(prop,Expression.Constant(“此处某物…”))

添加和连接是完全不同的过程。当您将两个字符串“相加”在一起时,您是在连接它们,因为对字符串进行数学加法没有意义

连接字符串的最佳方法是使用
String.Concat
。您可以使用
Expression.Call
生成方法表达式:

// 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);

添加字符串既不是表达式显式处理的类型之一(对于数值原语也是如此),也不会因为重载
+
(因为
string
没有此类重载)而起作用,因此需要显式定义重载时应调用的方法:

Expression.Add(
  prop,
  Expression.Constant(" Something here...")
  typeof(string).GetMethod("Concat", new []{typeof(string), typeof(string)}))
这使得采用两个字符串参数的
string.Concat的重载成为所使用的方法


您也可以使用
expression.Call
,但这会使您的
+
意图保持明确(这也是C#编译器在生成表达式时所做的工作)。

您的字典是否将名字作为字符串?{Key:“FirstName”,Value:“Andoni”}?
String.Join
不同于串联字符串
String.Join(a,b)
将产生
b
@Rob我正在找出使用
String.Concat
而不是
String.Join
,但我确实想指出
Join
Concat
没有那么大的不同
Join
只是将由给定分隔符分隔的字符串数组连接在一起,分隔符可以是空字符串<代码>字符串。Join(“,“a”,“b”)
将返回
“ab”
@Rob,因此,虽然我当前的代码不是最佳的,但它仍然完全可用。它现在将参数的定义更改为
字符串,字符串[]
,而不是
字符串,字符串
。看看第一个定义——第二个参数是数组,我希望
'a',['b','c']
返回
abc
,因为它应该是串联的,但实际上会返回
bac
。实际上,
a,[b]
将返回
b
如果这不是最好的方法,那么你不应该说这是最好的方法。也许这不是很重要,但对于编译,在第二个参数的末尾添加逗号(,)。