c# - 从 Int 到字符串的 LINQ 表达式转换/连接

标签 c# asp.net linq c#-4.0 asp.net-mvc-4

我想连接两个表达式作为最终表达式

Expression<Func<T, string>>

所以我创建的表达式 belwo 代码仅适用于字符串类型,如果我将 memberExpression 作为 Int32 或 DateTime 抛出异常

“System.Int32”类型的表达式不能用于方法“System.String Concat(System.String, System.String)”的“System.String”类型的参数

如果我将表达式转换为

var conversion = Expression.Convert(memberExpression, typeof (string));

getting No coercion operator is defined between types 'System.Int32' and 'System.String'.

请帮我解决

代码

MethodInfo bodyContactMethod = typeof (string).GetMethod("Concat",new[] {typeof (string), typeof (string)});

ParameterExpression parameter = Expression.Parameter(typeof (T));

body = Expression.Call(bodyContactMethod, cons, memberExpression);

return Expression.Lambda<Func<T, string>>(body, parameter);

最佳答案

您可以尝试转换为对象然后调用 ToString(),而不是尝试转换为字符串,就像您正在做的那样:

var converted = member.ToString();

作为表达式,它看起来像这样:

var convertedExpression = Expression.Call(
                     Expression.Convert(memberExpression, typeof(object)),
                     typeof(object).GetMethod("ToString"));

关于c# - 从 Int 到字符串的 LINQ 表达式转换/连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17862314/

相关文章:

asp.net - Web 应用程序最方便的阿拉伯字体

c# - 数组中数字的排列

c# - 使用 Linq 不存在

c# - 试图用C#制作计算器。这是怎么了?

c# - Entity Framework 的导航属性为空

c# - 当一个从 DBContextBase 读取而另一个从 DomainDBContext 读取时,从 2 个不同项目中的类访问 DBContext

c# - 为 HashSet<Tuple<TO, int>> 编写 IEqualityComparer

javascript - 在 Gmap 上使用 OverlappingMarkerSpiderfier 时如何取消页面加载时的标记

c# - 导出大量数据

c# - LINQ 如何根据给定条件对项目进行排序?