尝试使用表达式树创建以下表达式(希望得到帮助)
List<string> lstName = dt_Name.Select(y => y.Name);
List<string> lstLabName = dt_Label.Select(x => x.LabelName).Where(p => p.LabelName.StartsWith(lstName + '_'));
我希望它实际上遍历所有lstName并找到符合条件的lstLabName中的所有实例。
到目前为止我提出的代码是:
private BinaryExpression CreateBinaryExpression(string buildName)
{
// x.LabelName
var param = Expression.Parameter(typeof(dt_Label), "x");
var key = param.GetType().GetProperty("LabelName");
var left = Expression.MakeMemberAccess(param, key);
//ParameterExpression left = Expression.Parameter(typeof(string), "p"); //p
ConstantExpression constantExpression = Expression.Constant(buildName, typeof(string));
// x.LabelName == buildName
return Expression.MakeBinary(ExpressionType.Equal, left, constantExpression);
}
private BinaryExpression CalculateLambdaExp(List<string> lstBuildName)
{
BinaryExpression binaryExpression = CreateBinaryExpression(lstBuildName[0]);
if (lstBuildName.Count() > 1)
{
List<string> lstnStr = lstBuildName;
lstnStr.RemoveAt(0);
BinaryExpression calculatedLambdaExp = CalculateLambdaExp(lstnStr);
binaryExpression = Expression.MakeBinary(ExpressionType.AndAlso, binaryExpression, calculatedLambdaExp);
}
return binaryExpression;
}
private List<string> RunLambdaExpression(List<string> BuildName)
{
ParameterExpression left = Expression.Parameter(typeof(string), "p"); //p
var factorial = Expression.Lambda<Func<List<string>, List<string>>>(CalculateLambdaExp(BuildName), left);
var n = factorial.Compile()(BuildName);
List<string> lst = n.ToList();
return lst;
}
我遇到了大量的运行时错误。我将不胜感激。
计算了大部分内容:
将CreateBinaryExpression函数更改为:
private Expression CreateBinaryExpression(string buildName)
{
// x.LabelName
var param = Expression.Parameter(typeof(dt_Label), "x");
var key = typeof(dt_Label).GetProperty("LabelName");
var left = Expression.MakeMemberAccess(param, key);
ConstantExpression constantExpression = Expression.Constant(buildName + '_', typeof(string));
//x.LabelName.startsWith(buildName_)
MethodInfo mi = typeof(string).GetMethod("StartsWith", new Type[] { typeof(string) });
Expression call = Expression.Call(left, mi, constantExpression);
return call;
};
并更改了对函数的所有引用以接收Expression而不是BinaryExpression
答案 0 :(得分:3)
这一行是个问题
var key = param.GetType().GetProperty("LabelName");
param.GetType()
将返回没有System.Linq.Expressions.ParameterExpression
属性的LabelName
。
您应该使用typeof(dt_Label).GetProperty("LabelName")