Lambda根据属性名字选择或筛选

时间:2024-10-29 09:34:14
 using System;
using System.Linq.Expressions; internal class LambdaHelper
{
/// <summary>
/// 指定属性名字选择指定的属性
/// </summary>
/// <typeparam name="TIn">实体类型</typeparam>
/// <typeparam name="TOut">属性类型</typeparam>
/// <param name="propertyName">属性名称</param>
/// <returns></returns>
public static Func<TIn, TOut> CreatePropertyAccessor<TIn, TOut>(string propertyName)
{
var param = Expression.Parameter(typeof(TIn));
var body = Expression.PropertyOrField(param, propertyName);
return Expression.Lambda<Func<TIn, TOut>>(body, param).Compile();
} /// <summary>
/// 指定属性名称和属性值对实体类进行过滤
/// 用法:var q = db.Where(MakeFilter("ID", 1));
/// </summary>
/// <typeparam name="EType"></typeparam>
/// <param name="propertyName"></param>
/// <param name="value"></param>
/// <returns></returns>
public static Expression<Func<EType, bool>> MakeFilter<EType>(string propertyName, object value)
{
var type = typeof(EType); var property = type.GetProperty(propertyName); var parameter = Expression.Parameter(type, "p");
var propertyAccess = Expression.MakeMemberAccess(parameter, property);
var constantValue = Expression.Constant(value); var equality = Expression.Equal(propertyAccess, constantValue); return Expression.Lambda<Func<EType, bool>>(equality, parameter);
} /*用法:
var name1 = CreatePropertyAccessor<Obj, string>("Name");
var name2 = CreatePropertyAccessor<Obj, string>("Name2");
var name3 = CreatePropertyAccessor<Obj, string>("Name3"); var o = new Obj() // Obj is a type with those three properties
{
Name = "foo",
Name2 = "bar",
Name3 = "baz"
}; Console.WriteLine(name1(o)); // "foo"
Console.WriteLine(name2(o)); // "bar"
Console.WriteLine(name3(o)); // "baz" */
}