我需要从数据库表中获取两个字段(使用 linq-to-sql 检索),一个字段是日期时间(并且是固定字段),另一个始终是小数,但字段可以不同。
该表包含每天处理两次并以不同货币处理的货币数据,因此可能包含 AM_USD、PM_USD、AM_EUR 等字段。我需要获取数据,例如 PM_USD 的日期列表或 PM_USD 的日期列表AM_EUR。
例如,我希望能够使用 lambda 表达式调用数据(这是一个精简的示例):
data = TableData.Select(x=>new {x.DateTimeAdded, x.[**field name as string**]});
我一直在尝试编写一个函数来执行此操作,但失败得很惨。
我管理过的最接近的是:
private Func<TableData, KeyValuePair<DateTime, decimal>> CreateSelect(string FieldName)
{
var parameterExp = Expression.Parameter(typeof(TableData), "sel");
var dateParameter = Expression.Parameter(typeof(DateTime), "DateTimeAdded");
var fieldParameter = Expression.Parameter(typeof(decimal), FieldName);
ConstructorInfo constructorInfo = typeof(KeyValuePair<DateTime, decimal>).GetConstructor(new[] { typeof(DateTime), typeof(decimal) });
NewExpression constructExpression = Expression.New(constructorInfo, new ParameterExpression[] { dateParameter, fieldParameter});
var lambda = Expression.Lambda<Func<TableData, KeyValuePair<DateTime, decimal>>>( constructExpression, parameterExp);
return lambda.Compile();
}
失败并显示“System.InvalidOperationException:Lambda 参数不在范围内”。
我确信我遗漏了一些明显的东西,或者以错误的方式处理它。
有什么想法吗?
谢谢
最佳答案
x.Foo
是 x
(属性或字段)的成员,而不是参数:
private Func<TableData, KeyValuePair<DateTime, decimal>> CreateSelect(string FieldName)
{
var parameterExp = Expression.Parameter(typeof(TableData), "sel");
var dateProp = Expression.PropertyOrField(parameterExp, "DateTimeAdded");
var fieldProp = Expression.PropertyOrField(parameterExp, FieldName);
ConstructorInfo constructorInfo = typeof(KeyValuePair<DateTime, decimal>).GetConstructor(new[] { typeof(DateTime), typeof(decimal) });
NewExpression constructExpression = Expression.New(constructorInfo, new [] { dateProp, fieldProp});
var lambda = Expression.Lambda<Func<TableData, KeyValuePair<DateTime, decimal>>>( constructExpression, parameterExp);
return lambda.Compile();
}
关于c# - 使用 Lambda 表达式从字段名称中选择不同的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4214881/