C#过滤对象的集合

本文关键字:集合 对象 过滤 | 更新日期: 2023-09-27 18:26:47

我正在编写一个方法,该方法基于以下过滤器返回ProductPeriod对象的集合:

DateTime? from
DateTime? to
bool? includeActive
bool? includeInactive

ProductPeriod对象如下所示:

public class ProductPeriod
{
    public int Id { get; set; }
    public string Name
    public DateTime StartDate { get; set; }
    public DateTime EndDate { get; set; }
    public bool IsActive { get; set; }
}

因此,客户可以选择截止日期和/或起始日期,和/或包括活动期和/或不活动期。这为过滤提供了很多场景,这构成了一个相当大的方法,我开始写(但还没有完成):

public IEnumerable<ProductPeriod> GetFilteredProductPeriods(DateTime? from,     DateTime? to, bool? includeActive, bool? includeInactive)
{            
    // 1. from date only
    if(from.HasValue && to == null && includeActive == null && includeInactive == null)
        return _entities.ProductPeriods.Where(x => x.StartDate >= from.Value).ToList();
    // 2. from and to date
    if(from.HasValue && to.HasValue && includeActive == null && includeInactive == null)
        return _entities.ProductPeriods.Where(x => x.StartDate >= from.Value && x.EndDate <= to.Value).ToList();
    // 3. to date only
    if (to.HasValue && from == null && includeActive == null && includeInactive == null)
        return _entities.ProductPeriods.Where(x => x.EndDate <= to.Value).ToList();
    // 4. from date and show active
    if (from.HasValue && (includeActive != null && includeActive.Value) && to == null && includeInactive == null)
        return _entities.ProductPeriods.Where(x => x.StartDate >= from.Value && x.IsActive).ToList();
    // 5. from, to and show active
    if (from != null && to != null && (includeActive != null && includeActive.Value) && includeInactive == null)
        return _entities.ProductPeriods.Where(x => x.StartDate >= from.Value && x.EndDate <= to.Value && x.IsActive).ToList();
    // 6. to date and show active
    if (to.HasValue && (includeActive != null && includeActive.Value) && from == null && includeInactive == null)
        return _entities.ProductPeriods.Where(x => x.EndDate <= to.Value && x.IsActive).ToList();
    // 7. .... and so on, so forth..
}

我想知道是否有一种我不知道的更好/更聪明的方法可以做到这一点?即某种通用方式?:-)

提前谢谢。

C#过滤对象的集合

是的,肯定有更好的方法。您应该使用在LINQ:中建立查询的方式

public IEnumerable<ProductPeriod> GetFilteredProductPeriods
    (DateTime? from, DateTime? to, bool? includeActive, bool? includeInactive)
{
    IQueryable<ProductPeriod> query = _entities.ProductPeriods;
    if (from != null)
    {
        query = query.Where(x => x.StartDate >= from.Value);
    }
    if (to != null)
    {
        query = query.Where(x => x.EndDate >= to.Value);
    }
    if (includeActive == false)
    {
        query = query.Where(x => !x.IsActive);
    }
    if (includeInactive == false)
    {
        query = query.Where(x => x.IsActive);
    }
    return query.ToList();
}

请注意,设置includeInactive=falseincludeActive=false不会给您任何结果。。。您可能希望将其更改为单个参数,即false(仅处于非活动状态)、true(仅处于活动状态)和null(全部)。