》》》可以借助 LINQPad工具
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using System.Transactions;
namespace EFDemo
{
public class Product
{
public string Product_Name { get; set; }
public int Product_Price { get; set; }
}
class Program
{
static void Main(string[] args)
{
List<Product> prolist = new List<Product>() {
new Product(){ Product_Name="苹果手机",Product_Price=5999},
new Product(){ Product_Name="华为手机",Product_Price=4999},
new Product(){ Product_Name="华为手机",Product_Price=6999},
new Product(){ Product_Name="苹果手机",Product_Price=9999}
};
var result1= prolist.Where(c =>{ return c.Product_Name == "苹果手机" && c.Product_Price > 6000; });
foreach (var r in result1)
{
Console.WriteLine($"产品名称:{r.Product_Name} 价格:{r.Product_Price}");
}
var item=Expression.Parameter(typeof(Product), "item");
var item_name = Expression.Property(item, "Product_Name");
var item_price= Expression.Property(item, "Product_Price");
var query_Name = Expression.Constant("苹果手机");
var query_Price = Expression.Constant(6000);
var c1 = Expression.Equal(item_name, query_Name);
var c2 = Expression.GreaterThan(item_price, query_Price);
var cc = Expression.And(c1, c2);
var lambda_expression = Expression.Lambda<Func<Product, bool>>(cc, item);
var reuslt = lambda_expression.Compile();
Console.WriteLine(lambda_expression.ToString());
var res = prolist.Where(reuslt);
foreach (var r in res)
{
Console.WriteLine($"产品名称:{r.Product_Name} 价格:{r.Product_Price}");
}
Console.ReadKey();
}
}
}
》》》表达式树 编译之后 才是委托
利用表达式树 对象的映射
》》》定义一个泛型静态类 ExpressionMapper<Tin ,Tout>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
namespace EFDemo
{
public class ExpressionMapper<Tin ,Tout>
{
private static Func<Tin, Tout> _Func = null;
static ExpressionMapper()
{
ParameterExpression paramExp = Expression.Parameter(typeof(Tin), "p");
List<MemberBinding> memberBindingList = new List<MemberBinding>();
//绑定属性
foreach (var item in typeof(Tout).GetProperties())
{
MemberExpression member = Expression.Property(paramExp, typeof(Tin).GetProperty(item.Name));
MemberBinding memberBinding = Expression.Bind(item,member);
memberBindingList.Add(memberBinding);
}
//绑定字段
foreach (var item in typeof(Tout).GetFields())
{
MemberExpression member = Expression.Field(paramExp, typeof(Tin).GetField(item.Name));
MemberBinding memberBinding = Expression.Bind(item, member);
memberBindingList.Add(memberBinding);
}
//创建新对象并初始化
MemberInitExpression memberInitExp = Expression.MemberInit(Expression.New(typeof(Tout)),memberBindingList.ToArray());
Expression<Func<Tin, Tout>> funcExp = Expression.Lambda<Func<Tin, Tout>>(memberInitExp, new ParameterExpression[] { paramExp });
_Func = funcExp.Compile();
}
public static Tout Mapper(Tin t)
{
return _Func(t);
}
}
}