C# 应用筛选条件过滤产品列表 - IQueryable<Product> 筛选器
这段代码是一个用于应用筛选条件的方法,它接收一个 IQueryable<Product> 类型的查询参数 query,并根据传入的筛选条件对该查询进行过滤。
参数解释:
FilterText: 用于筛选的文本ProductName: 产品名称StoreId: 商店IDStoreName: 商店名称ProductItemId: 产品项IDProductItem: 产品项ProductTag: 产品标签Price: 价格PriceMin: 最低价格PriceMax: 最高价格Stock: 库存IsAvailable: 是否可用LeadTime: 配送时间Image: 图片Evaluate: 评估Remarks: 备注SortOrder: 排序顺序
代码解释:
- 方法的返回类型为
IQueryable<Product>,表示返回一个可查询的产品列表。 - 使用
query.WhereIf()方法来根据条件进行过滤,只有当条件为真时才会应用该过滤条件。 - 使用
Contains()方法来判断ProductName和StoreName是否包含指定的文本。 - 使用
==运算符来比较StoreId和ProductItemId。 - 使用
>=和<=运算符来比较Price和PriceMin/PriceMax。 - 使用
==运算符来比较Stock和LeadTime。 - 使用
==运算符来比较Image和Evaluate。 - 使用
==运算符来比较Remarks和SortOrder。
总的来说,这段代码根据传入的筛选条件对查询进行了过滤,并返回满足条件的产品列表。
protected virtual IQueryable<Product> ApplyFilter(
IQueryable<Product> query,
string FilterText = null,
string ProductName = null,
Guid? StoreId = null,
string StoreName = null,
Guid? ProductItemId = null,
string ProductItem = null,
string ProductTag = null,
decimal? Price = null,
decimal? PriceMin = null,
decimal? PriceMax = null,
double? Stock = null,
bool? IsAvailable = null,
double? LeadTime = null,
string Image = null,
double? Evaluate = null,
string Remarks = null,
int? SortOrder = null)
{
return query
.WhereIf(!string.IsNullOrWhiteSpace(ProductName), e => e.ProductName.Contains(ProductName))
.WhereIf(StoreId.HasValue, e => e.StoreId == StoreId.Value)
.WhereIf(!string.IsNullOrWhiteSpace(StoreName), e => e.StoreName.Contains(StoreName))
.WhereIf(ProductItemId.HasValue, e => e.ProductItemId == ProductItemId.Value)
.WhereIf(!string.IsNullOrWhiteSpace(ProductItem), e => e.ProductItem.Contains(ProductItem))
.WhereIf(!string.IsNullOrWhiteSpace(ProductTag), e => e.ProductTag == ProductTag)
.WhereIf(Price.HasValue, e => e.Price == Price.Value)
.WhereIf(PriceMin.HasValue, e => e.Price >= PriceMin.Value)
.WhereIf(PriceMax.HasValue, e => e.Price <= PriceMax.Value)
.WhereIf(Stock.HasValue, e => e.Stock == Stock.Value)
.WhereIf(IsAvailable.HasValue, e => e.IsAvailable == IsAvailable.Value)
.WhereIf(LeadTime.HasValue, e => e.LeadTime == LeadTime.Value)
.WhereIf(!string.IsNullOrWhiteSpace(Image), e => e.Image == Image)
.WhereIf(Evaluate.HasValue, e => e.Evaluate == Evaluate.Value)
.WhereIf(!string.IsNullOrWhiteSpace(Remarks), e => e.Remarks == Remarks)
.WhereIf(SortOrder.HasValue, e => e.SortOrder == SortOrder.Value);
}
原文地址: https://www.cveoy.top/t/topic/p0B8 著作权归作者所有。请勿转载和采集!