C# Linq表达式-“;变量";类型为';System.Data.DataRow';从范围中引用”&引用;但它没有定义

C# Linq表达式-“;变量";类型为';System.Data.DataRow';从范围中引用”&引用;但它没有定义,c#,linq,lambda,tuples,expression,C#,Linq,Lambda,Tuples,Expression,我试图在运行时使用datarow字段动态构建一个带有元组的lambda,以传递给linq groupby。我得到一个异常“变量”,类型为“System.Data.DataRow”“referenced from scope”,但它没有定义 MethodInfo fieldMI = typeof(DataRowExtensions).GetMethod("Field",new Type[] { typeof(DataRow), typeof(DataColumn) }.MakeGenericMet

我试图在运行时使用datarow字段动态构建一个带有元组的lambda,以传递给linq groupby。我得到一个异常“变量”,类型为“System.Data.DataRow”“referenced from scope”,但它没有定义

MethodInfo fieldMI = typeof(DataRowExtensions).GetMethod("Field",new Type[] { typeof(DataRow), typeof(DataColumn) }.MakeGenericMethod(typeof(string));
ParameterExpression fieldParameter = Expression.Parameter(typeof(DataRow));

Type[] parameterTypes = new Type[fields.Count];
MethodCallExpression[] methodCallExpressions = new MethodCallExpression[fields.Count];

for(int i = 0; i < fields.Count; i++) {
parameterTypes[i] = typeof(string);
Expression dataElement = Expression.Constant(dc[i], typeof(DataColumn));
methodCallExpressions[i] = Expression.Call(null, fieldMI, new Expression[] { fieldParameter, dataElement});
}
var tupleTypeDefinition = typeof(Tuple).Assembly.GetType("System.Tuple`" = fields.Count);
var tupleType = tupleTypeDefinition.MakeGenericType(parameterTypes);
var constructor = tupleType.GetConstructor(parameterTypes);
var param = Expression.Parameter(typeof(DataRow));
var body = Expression.New(constructor, methodCallExpressions);
var func = Expression.Lambda<Func<DataRow, object>>(body,param).Compile();
MethodInfo fieldMI=typeof(DataRowExtensions).GetMethod(“Field”,新类型[]{typeof(DataRow),typeof(DataColumn)}.MakeGenericMethod(typeof(string));
ParameterExpression fieldParameter=Expression.Parameter(typeof(DataRow));
Type[]参数类型=新类型[fields.Count];
MethodCallExpression[]methodCallExpressions=新的MethodCallExpression[fields.Count];
for(int i=0;i
我终于找到了答案-我创建了一个新的DataRow参数(param),而不是使用以前创建的相同参数(fieldParameter)。现在它可以工作了。

数据行必须与数据表关联。您不能调用数据行构造函数。数据表在查询中的位置在哪里?抱歉-我没有真正了解-我没有调用我可以看到的数据行构造函数…我正在使用调用数据上的Field方法所产生的字符串参数调用元组构造函数行。lambda正在接收一个datarow而不是datatable。datarow来自的表在哪里?如果没有调用datarow构造函数,就不能有datarow。因此datarow为null并导致错误,因为该行不是来自表。您能建议所需的更改吗?要提取数据的对象在哪里ata from?Linq是一个查询(这就是q所代表的),因此您需要为查询输入数据。数据在哪里?在使用DataRow之前,您需要使用现有DataTable或创建新DataTable。如果您没有DataTable,请绑定到其他类型的对象。