<分区>
我正在编写一个方法,它根据以下过滤器返回 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..
}
我想知道是否有我不知道的更好/更智能的方法来做到这一点? IE。某种通用的方式? :-)
提前致谢。