表达式树是一种不错的特性,但它们有哪些实际用途呢?它们可以用于代码生成、元编程或其他类似的应用吗?
表达式树是一种不错的特性,但它们有哪些实际用途呢?它们可以用于代码生成、元编程或其他类似的应用吗?
我刚刚创建了一个使用表达式树的通用过滤器函数,想要与大家分享...
开始
var allFiltered= Filter(AllCustomer, "Name", "Moumit");
public static List<T> Filter<T>(this List<T> Filterable, string PropertyName, object ParameterValue)
{
ConstantExpression c = Expression.Constant(ParameterValue);
ParameterExpression p = Expression.Parameter(typeof(T), "xx");
MemberExpression m = Expression.PropertyOrField(p, PropertyName);
var Lambda = Expression.Lambda<Func<T, Boolean>>(Expression.Equal(c, m), new[] { p });
Func<T, Boolean> func = Lambda.Compile();
return Filterable.Where(func).ToList();
}
再来一个
string singlePropertyName=GetPropertyName((Property.Customer p) => p.Name);
public static string GetPropertyName<T, U>(Expression<Func<T, U>> expression)
{
MemberExpression body = expression.Body as MemberExpression;
// if expression is not a member expression
if (body == null)
{
UnaryExpression ubody = (UnaryExpression)expression.Body;
body = ubody.Operand as MemberExpression;
}
return string.Join(".", body.ToString().Split('.').Skip(1));
}
使其更具扩展性
string multiCommaSeparatedPropertyNames=GetMultiplePropertyName<Property.Customer>(c => c.CustomerId, c => c.AuthorizationStatus)
public static string GetMultiplePropertyName<T>(params Expression<Func<T, object>>[] expressions)
{
string[] propertyNames = new string[expressions.Count()];
for (int i = 0; i < propertyNames.Length; i++)
{
propertyNames[i] = GetPropertyName(expressions[i]);
}
return propertyNames.Join();
}
我知道也可以使用反射来实现,但这种方法非常快,或者说,在第一次编译后相当于 lambda表达式。 第一次迭代只需要平均10毫秒。所以这就是Expression Tree的神奇之处。简单而棒极了(我认为)!
Bar.Baz
作为 string
。 - Moumitstring.Join(".", body.Split('.').Last()
就可以解决问题,不是吗? - Josh Gust我使用它们创建动态查询,无论是用于对数据进行排序还是过滤。以下是一个示例:
IQueryable<Data.Task> query = ctx.DataContext.Tasks;
if (criteria.ProjectId != Guid.Empty)
query = query.Where(row => row.ProjectId == criteria.ProjectId);
if (criteria.Status != TaskStatus.NotSet)
query = query.Where(row => row.Status == (int)criteria.Status);
if (criteria.DueDate.DateFrom != DateTime.MinValue)
query = query.Where(row => row.DueDate >= criteria.DueDate.DateFrom);
if (criteria.DueDate.DateTo != DateTime.MaxValue)
query = query.Where(row => row.DueDate <= criteria.DueDate.DateTo);
if (criteria.OpenDate.DateFrom != DateTime.MinValue)
query = query.Where(row => row.OpenDate >= criteria.OpenDate.DateFrom);
var data = query.Select(row => TaskInfo.FetchTaskInfo(row));
您可以使用它们构建自己的LINQ提供程序,用于像Google、Flickr或Amazon这样的网站,也可以用于您自己的网站或其他数据提供程序。