带Or表达式的通用Lambda表达式调用

时间:2016-04-06 18:17:44

标签: .net generics lambda

我有一个扩展方法,可以过滤掉一个列表,只返回居住在蒙特利尔和纽约的人。

var persons = List<Person>();
var acceptedCities = new List{"Montreal", "New York"};

myList.Where(p => p.City, acceptedCities );

扩展方法如下所示

 public static IQueryable<Tsource> Where<Tsource, Tproperty>(this IQueryable<Tsource> source, Expression<Func<Tsource, Tproperty>> property, IList<int?> accpetedValues)
        {
            var propertyName = ((MemberExpression)property.Body).Member.Name;

            if (propertyName == null)
                throw new ArgumentException();

            if (accpetedValues == null || string.IsNullOrEmpty(propertyName))
                return source;

            var item = Expression.Parameter(typeof(Tsource), "item");
            var selector = Expression.PropertyOrField(item, propertyName);

            var predicate = Expression.Lambda<Func<Tsource, bool>>(Expression.Call(typeof(Enumerable), "Contains", new[] { typeof(Tproperty) },
                                             Expression.Constant(accpetedValues), selector), item);
            return source.Where(predicate);
        }

假设某个人没有指定任何城市,我也需要得到它们,然后我想修改我的方法来添加OR exrpession,但我不能让它工作。

  var contains = Expression.Call(typeof(Enumerable), "Contains", new[] { typeof(Tproperty) },
                                             Expression.Constant(accpetedValues), selector);
            var isNull = Expression.Call(typeof(int?), "Equals", new[] { typeof(Tproperty) }, Expression.Constant(null), selector);
            var orExpression = Expression.Or(contains, isNull);

            var predicate = Expression.Lambda<Func<Tsource, bool>>(orExpression, item);

1 个答案:

答案 0 :(得分:0)

我把它修好了

<div class="sidebar">
<h1>
MY TITLE
</h1>
</div>


.sidebar {
    border-right: 1px solid black;
    height: 600px;
    width: 186px;
}