static Expression<Func<T, bool>> Lambda<T>() where T : class
{
//添加表达式参数, (p) => p.ParentId == 0 表达式中的参数 p, p 为可自定义参数名称
ParameterExpression[] parameters = { Expression.Parameter(typeof(T), "p") };
//定义表达式左侧内容, (p) => p.ParentId == 0 表达式中 p.ParentId,
//传入表达式参数, 反射拿到的属性, typeof(T).GetProperty("ParentId").GetGetMethod() 可直接写 "ParentId"
var member = Expression.Property(parameters[0], typeof(T).GetProperty("ParentId").GetGetMethod());
//定义表达式左侧内容, (p) => p.ParentId == 0 表达式中 0, 常量内容
ConstantExpression constant = Expression.Constant(0, typeof(int));
//Expression.Equal 定义等号, parameters传入表达式参数 p
return Expression.Lambda<Func<T, bool>>(Expression.Equal(member, constant), parameters);
}
//调用lambda查询
itemList.Where(Lambda<T>().Compile()).FirstOrDefault();
另一个调用方法的例子:
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace ExpressionLambda
{
class Program
{
static void Main(string[] args)
{
Exec1();
Exec2();
Console.Read();
}
static void Exec1()
{
var a = Expression.Constant(1);
var b = Expression.Constant(2);
var add = Expression.Add(a, b);
//创建 lambda 表达式
Expression<Func<int>> funcExpression = Expression.Lambda<Func<int>>(add);
//编译 lambda 表达式
Func<int> func = funcExpression.Compile();
Console.WriteLine(func());
}
static void Exec2()
{
var b = Expression.Constant(2);
var intObj = new IntObj()
{
Value = 10
};
ParameterExpression expA = Expression.Parameter(typeof(IntObj), "a"); //参数a
MethodCallExpression expCall = Expression.Call(null,
typeof(Program).GetMethod("GetIntObjValue", BindingFlags.Static | BindingFlags.Public),
expA); //Math.Sin(a)
//Expression<Func<IntObj, int>> exp = Expression.Lambda<Func<IntObj, int>>(expCall, expA);
var add = Expression.Add(expCall, b);
//创建 lambda 表达式
Expression<Func<IntObj,int>> funcExpression = Expression.Lambda<Func<IntObj,int>>(add,expA);
//编译 lambda 表达式
Func<IntObj,int> func = funcExpression.Compile();
Console.WriteLine(func(intObj));
}
public static int GetIntObjValue(IntObj intObj)
{
return intObj.Value;
}
}
public class IntObj
{
public int Value { get; set; }
}
}
网友评论