使用lambda防爆pression来选择字段名不同领域 [英] Using Lambda Expression to Select different fields from field names
问题描述
我需要从数据库表中的两个字段(被检索使用LINQ到SQL),一个场是一个日期时间(并且是一个固定的场),另一种是始终小数,但该字段可以不同。
I need to get two fields from a database table (retrieved using linq-to-sql), one field is a datetime (and is a fixed field) and the other is always a decimal, but the field can be different.
该表保存被处理,每天两次,并在不同的货币,以便能有字段,如AM_USD,PM_USD,AM_EUR等货币数据,我需要获取数据,如对PM_USD日期或对日期的列表AM_EUR。
The table holds currency data which is processed twice a day and in different currencies so could have fields such as AM_USD, PM_USD, AM_EUR etc. And I need to get data such as a list of the date against PM_USD or the date against AM_EUR.
我希望能够调用例如使用一个lambda前pression(这是一个剥离出来的例子)中的数据:
I would like to be able to call the data using a lambda expression for example (this is a stripped out example):
data = TableData.Select(x=>new {x.DateTimeAdded, x.[**field name as string**]});
我一直在试图写一个函数来做到这一点,和我惨淡经营失败。
I have been trying to write a function to do this, and am failing dismally.
我设法最接近的是:
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参数不在范围内。
Which fails with "System.InvalidOperationException: Lambda Parameter not in scope".
我敢肯定,我缺少明显的东西,或绕了错误的方式。
I'm sure I missing something obvious, or going about it wrong way.
任何想法?
谢谢
ŧ
推荐答案
x.Foo
是成员的的X
(属性或字段),而不是一个参数:
x.Foo
is a member of x
(property or field), not a parameter:
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();
}
这篇关于使用lambda防爆pression来选择字段名不同领域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!