我正在编写一个方法,该方法根据以下过滤器返回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..
}
我想知道是否有更好/更聪明的方法来做到这一点,我不知道?即某种通用方式? : - )
提前致谢。
答案 0 :(得分:3)
是的,肯定有更好的方法。您应该使用在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=false
和includeActive=false
将不会给您带来任何结果......您可能希望将其更改为false
的单个参数(仅处于非活动状态),{{1 (仅限活动),true
(全部)。