您的位置:首页 > 其它

将不确定变为确定~表达式树是否可以有个集合,条件过滤有了新方向

2012-06-07 13:49 351 查看
回到目录

对于我之前项目中的统一条件过滤采用了dictinary来实现的,优点就是方法签名统一了,缺点不用说,就是字典的键容易写错,感觉一进入.net3.5之后,一切都要和Expression联系在一起,我们在创建一个Expression(表达式树)时,可以使用lambda表达式去创建,很容易:

Expression<Func<string, bool>> predicate= name=>name=="zzl";


可以看到,它其它由一个委托组成,输入参数是个字符,输出是个布尔值,在LINQ中这种技术被广泛的使用在扩展方法中,如Where扩展方法:

public static IQueryable<TSource> Where<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, bool>> predicate)
{
if (source == null)
{
throw System.Linq.Error.ArgumentNull("source");
}
if (predicate == null)
{
throw System.Linq.Error.ArgumentNull("predicate");
}
return source.Provider.CreateQuery<TSource>(Expression.Call(null, ((MethodInfo) MethodBase.GetCurrentMethod()).MakeGenericMethod(new Type[] { typeof(TSource) }), new Expression[] { source.Expression, Expression.Quote(predicate) }));
}


无可厚非,表达式树的出现,lambda表达式的支持,是.net开发人员的福音,也是.net3.5中更大的亮点了。

说正文了,以前我的写统一的参数签名时,使用的是dictionary,代码中可以是这样的

      Common.VPredication vp = new Common.VPredication();
Common.PagingParam pp = new Common.PagingParam(page ?? 1, VConfig.WebConstConfig.PageSize);

vp.AddItem("userId", userID);
if (_gid != 0)
vp.AddItem("gid", _gid);


统一的方法签名:

Common.Page.PagedList<Entity.Res_Item> GetList(Common.VPredication vp, Common.PagingParam pp)


而有了表达式树的集合后,完成可以把过滤条件写在它里面,这样构建条件变成了这样:

       PredicateList<UserBases> zzl = new PredicateList<UserBases>();
zzl.Add(i => i.Name.Contains("zzl"));
zzl.Add(i => i.UserID == 1);
GetModel(zzl).ForEach(i => Console.WriteLine(i.UserID + i.Name));


而方法签名仍然是很统一,只是变成了表达式树的样子,有点强类型的味道,呵呵:

List<UserBases> GetModel(PredicateList<UserBases> param)


而PredicateList类型的原代码,我也公开一下吧,呵呵,大家一共分享:

  /// <summary>
/// 功能:条件过滤类
/// 作者:张占岭
/// 日期:2012-6-7
/// </summary>
public class PredicateList<TEntity> : IEnumerable<Expression<Func<TEntity, bool>>> where TEntity : class
{
List<Expression<Func<TEntity, bool>>> expressionList;
public PredicateList()
{
expressionList = new List<Expression<Func<TEntity, bool>>>();
}
/// <summary>
/// 添加到集合
/// </summary>
/// <param name="predicate"></param>
public void Add(Expression<Func<TEntity, bool>> predicate)
{
expressionList.Add(predicate);
}
/// <summary>
/// 从集合中移除
/// </summary>
/// <param name="predicate"></param>
public void Remove(Expression<Func<TEntity, bool>> predicate)
{
expressionList.Remove(predicate);
}
#region IEnumerable 成员

public IEnumerator GetEnumerator()
{
return expressionList.GetEnumerator();
}

#endregion

#region IEnumerable<Expression<Func<TEntity>>> 成员

IEnumerator<Expression<Func<TEntity, bool>>> IEnumerable<Expression<Func<TEntity, bool>>>.GetEnumerator()
{
return expressionList.GetEnumerator();
}

#endregion
}


回到目录
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: