Lambda代码问题
代码:class A
{
public int ID { get; set; }
public string Name { get; set; }
}
class Program
{
static void Main(string[] args)
{
var data = Enumerable.Repeat(0, 6).Select((x, i) => new A { ID = i / 2, Name = ((char)(i / 2 + 65)).ToString() });
Expression<Func<A, bool>> query1 = x => x.ID == 1;
Expression<Func<A, bool>> query2 = x => x.Name == "A";
var query = data.Where(Expression.Lambda(Expression.AndAlso((query1 as LambdaExpression).Body, (query2 as LambdaExpression).Body), (query1 as LambdaExpression).Parameters).Compile() as Func<A, bool>);
foreach (var item in query)
Console.WriteLine("{0} {1}", item.ID, item.Name);
}
}
出错
Unhandled Exception: System.InvalidOperationException: variable 'x' of type 'LinqStudyConsoleApp.A' referenced from scope '', but it is not defined
怎么办? --------------------编程问答-------------------- var query = data.Where(t=>(Expression.Lambda(Expression.AndAlso((query1 as LambdaExpression).Body, (query2 as LambdaExpression).Body), query1.Parameters.Union(query2.Parameters)).Compile() as Func<A, A, bool>)(t,t));
--------------------编程问答-------------------- 不是这几行的问题,是你其他地方有重复的x变量的定义吧,你找找 --------------------编程问答--------------------
Expression<Func<A, bool>> expr1 = x => x.ID == 0;
Expression<Func<A, bool>> expr2 = x => x.Name == "A";
var invokedExpr = Expression.Invoke(expr2, expr1.Parameters.Cast<Expression>());
var andAlsolam = Expression.Lambda<Func<A, bool>>(Expression.AndAlso(expr1.Body, invokedExpr), expr1.Parameters);
var query = data.Where(andAlsolam.Compile());
补充:.NET技术 , C#