Code
using System;
using System.Linq.Expressions;
using System.Linq;
using System.Data.Linq;
namespace KingRi.Test
{
public class Student
{
public Student(string name)
{
this.name = name;
}
private string name;
public string Name
{
get
{
return this.name;
}
set
{
this.name = value;
}
}
}
public class Client
{
static void Main()
{
//表达式树基础
/*
//Expression<Func<int, int, int>> expression = (a, b)=>a*b+2
ParameterExpression leftParam = Expression.Parameter(typeof(int), "a");
ParameterExpression rightParam = Expression.Parameter(typeof(int), "b");
BinaryExpression binaryLeft = Expression.Multiply(leftParam, rightParam);
ConstantExpression conRight = Expression.Constant(2, typeof(int));
BinaryExpression binaryBody = Expression.Add(binaryLeft, conRight);
LambdaExpression lambda = Expression.Lambda<Func<int, int, int>>(binaryBody, leftParam, rightParam);
Console.WriteLine(lambda.ToString());
*/
//动态构建Linq
/*
ParameterExpression c1= Expression.Parameter(typeof(Student), "std");
Expression condition = Expression.Constant(false);
string[] cs = {"ad", "ac"};
foreach (string c in cs)
{
Expression con = Expression.Call(
Expression.Property(c1, typeof(Student).GetProperty("Name")),
typeof(string).GetMethod("StartsWith", new Type[] { typeof(string) }),
Expression.Constant(c));
condition = Expression.Or(con, condition);
}
Expression<Func<Student, bool>> end =
Expression.Lambda<Func<Student, bool>>(condition, new ParameterExpression[] { c1 });
Console.WriteLine(end.ToString());
*/
//Expression.Call方法学习
Student[] stds = {
new Student("ac Zhang"),
new Student("ad Lisi"),
new Student("aa WangWu")
};
ParameterExpression param = Expression.Parameter(typeof(Student), "c");
Expression seletor = Expression.Property(param, typeof(Student).GetProperty("Name"));
Expression pred = Expression.Lambda(seletor, param);
Expression expr = Expression.Call(
typeof(Queryable),
"Select",
new Type[] { typeof(Queryable), typeof(Expression<>) },
Expression.Constant(stds),
pred);
//(null, ((MethodInfo) MethodBase.GetCurrentMethod()).MakeGenericMethod(new Type[] { typeof(TSource) }), new Expression[] { source.Expression, Expression.Quote(predicate) }));
IQueryable<string> query = stds.AsQueryable().Provider.CreateQuery<string>(expr);
DataContext db = new DataContext("");
System.Data.Common.DbCommand cmd = db.GetCommand(query);
Console.WriteLine(cmd.CommandText);
}
}
}