从lambda表达式中排除null或空字符串值

时间:2018-05-07 09:04:03

标签: c# lambda expression-trees specification-pattern

GetAll函数的应用程序中,我有一个名为CustomerModel的参数。我用它来对查询进行一些过滤,并使用规范模式来避免使用if-else

    public async Task<List<CustomerModel>> GetAllAsync(CustomerModel customer, Order order = Order.Ascending, int pageIndex = 1, int pageSize = int.MaxValue)
    {
        var skip = (pageIndex - 1) * pageSize;

        var filter = new CustomerNameSpecification(customer)
            .And(new CustomerNoSpecification(customer))
            .And(new CustomerCompanySpecification(customer))
            .And(new CustomerPhoneSpecification(customer))
            .And(new CustomerEmailSpecification(customer))
            .And(new CustomerAddressSpecification(customer))
            .Take(pageSize)
            .Skip(skip);

        var orderSpecification = new CustomerOrderSpecification(order);

        return await _customerRepository.GetAllAsync(filter, orderSpecification);
    }

例如,其中一个规范对象(CustomerNameSpecification):

public class CustomerNameSpecification : Specification<Customer>
{
    public CustomerModel Customer { get; set; }

    public CustomerNameSpecification(CustomerModel customerModel)
    {
        Customer = customerModel;
    }

    public override Expression<Func<Customer, bool>> AsExpression()
    {
        return customerFiler =>
            customerFiler.Name.Contains(Customer.Name);
    }
 }
  

更新

在规范模式中操作:

public class AndSpecification<T> : Specification<T> 
    where T : class
{
    private readonly ISpecification<T> _left;
    private readonly ISpecification<T> _right;

    public AndSpecification(ISpecification<T> left, ISpecification<T> right)
    {
        _left = left;
        _right = right;
    }

    public override Expression<Func<T, bool>> AsExpression()
    {
        var leftExpression = _left.AsExpression();
        var rightExpression = _right.AsExpression();

        var parameter = leftExpression.Parameters.Single();
        var body = Expression.AndAlso(leftExpression.Body, SpecificationParameterRebinder.ReplaceParameter(rightExpression.Body, parameter));

        return Expression.Lambda<Func<T, bool>>(body, parameter);
    }
  }
}

这些链在最后创建一个lambda表达式,存储库使用它来过滤查询。

CustomerModel的每个字段都有值时,此解决方案正常工作,但即使一个属性的值为空或空值,它也不起作用。

如何修复此问题并排除lambda表达式,其中我有一个空字符串值或空字符串值?

1 个答案:

答案 0 :(得分:2)

  

如何解决此问题并将lambda表达式排除在我所拥有的位置   null或空字符串值?

例如CustomerNameSpecification,要排除空值,您可以使用代码:

public override Expression<Func<Customer, bool>> AsExpression()
{
    return customerFiler => string.IsNullOrWhiteSpace(customerFiler.Name) ||
        customerFiler.Name.Contains(Customer.Name);
}

如果string.IsNullOrWhitespace(customerFiler.Name)返回true,则不会评估customerFiler.Name.Contains(Customer.Name);