什么是表达式树?
- 表达式是对于一段可执行代码的文字形式,它本身是不可以执行的。如BinaryExpression,ConstantExpression,LambdaExpression
下面的例子把两个表达式组建成了一个表达式树
Expression firstArg = Expression.Constant(2);
Expression secondArg = Expression.Constant(4);
Expression add = Expression.Add(firstArg, secondArg);
- 表达树的每个节点都是一个表达式,表达式树本身也是一个表达式。
看看下面例子:
{
//Create an object
public class User
{
public int ID
{
get;
set;
}
public string FirstName
{
get;
set;
}
public string LastName
{
get;
set;
}
}
}
Program类的方法,包含了一个输出函数和几个User集合的方法
private static void PrintNames(IEnumerable<User> users)
{
foreach (User user in users)
{
Console.WriteLine(user.FirstName + " " + user.LastName);
}
}
private static IQueryable<User> QueryableUsers()
{
return new List<User>
{
new User {ID = 1, FirstName = "Kevin", LastName = "Garnett"},
new User {ID = 2, FirstName = "Stephen", LastName = "Garnett"},
new User {ID = 3, FirstName = "Kevin", LastName = "Durant"}
}.AsQueryable();
}
private static User[] arrayUsers()
{
return new User[]
{
new User {ID = 1, FirstName = "Kevin", LastName = "Garnett"},
new User {ID = 2, FirstName = "Stephen", LastName = "Garnett"},
new User {ID = 3, FirstName = "Kevin", LastName = "Durant"}
};
}
private static List<User> ListUsers()
{
return new List<User>
{
new User {ID = 1, FirstName = "Kevin", LastName = "Garnett"},
new User {ID = 2, FirstName = "Stephen", LastName = "Garnett"},
new User {ID = 3, FirstName = "Kevin", LastName = "Durant"}
};
}
}
Main
static void Main(string[] args)
{
Expression<Func<User, bool>> FirstExp = (x => x.LastName == "Garnett");
Expression<Func<User, bool>> SecondExp = (x => x.FirstName == "Kevin");
var qusers = QueryableUsers();
var lusers = ListUsers();
var ausers = arrayUsers();
//表达式树只能放到Queryable里面使用,而且要于Where一起使用
var result1 = qusers.Where(FirstExp);
var result2 = lusers.Where(x => x.LastName == "Durant");
var result3 = ausers.Where(x => x.FirstName == "Kevin");
PrintNames(result1);
PrintNames(result2);
PrintNames(result3);
Console.ReadKey();
}
Result:
说明:
- Expression<Func<User, bool>>声明了这个表达式是一个参数为User并返回bool的Func<>
- 也可以直接运行表达式树, 但需要先编译,因为它本身只是一个表达式,并不能执行
Expression<Func<User, bool>> FirstExp = (x => x.LastName == "Garnett");
var result4 = FirstExp.Compile()(new User { ID = 4, FirstName = "Kenny", LastName = "Garnett" });
Console.WriteLine(result4);
//返回的是True