【发布时间】:2015-12-15 12:07:29
【问题描述】:
我正在编写一个基于以下过滤器返回 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。某种通用方式? :-)
提前致谢。
【问题讨论】:
-
您可以链接
Where()s,即ANDed。如果您声明IQueryable<ProductPeriod>,则可以这样做。请参阅duplicate (second answer)、entity framework: conditional filter、Linq: adding conditions to the where clause conditionally 等。编辑:再次outSkeeted ...
标签: c# entity-framework