gpt4 book ai didi

c# - 正确过滤 Linq 查询

转载 作者:太空宇宙 更新时间:2023-11-03 21:54:35 28 4
gpt4 key购买 nike

我有这个查询,它从一堆商店中检索销售额,并将它们作为列表返回。在我的报告请求屏幕上,用户可以按多个 ID 进行过滤 - ShopOwnerId、ShopRegionId、ShopTypeCode 等。

我的查询结构为获取选定日期之间的所有销售额,然后根据选择进行过滤。这显然是非常低效的。 :

private List<Sales> GetFilteredListOfSales(Request reportreq)
{
ModelContainer ctn = new ModelContainer();
List<ShopSale> shopsSales = new List<shopsale>();

// If no filters are selected
//
if (reportreq.RegionalId == null && reportreq.OwnerId == null && reportreq.ShopTypeCode == null)
{
shopsSales = (from sale in ctn.ShopSales
where sale.DateSold >= reportreq.FromDate && sale.DateSold <= reportreq.ToDate
select sale).ToList();
}


// If the regional ID has a value...
//
if (reportreq.RegionalId.HasValue)
{
shopsSales = (from sale in ctn.ShopSales
where sale.Shop.Owner.RegionalId == reportreq.RegionalId
&& sale.DateSold >= reportreq.FromDate && sale.DateSold <= reportreq.ToDate
select sale).ToList();
}

// If the owner ID has a value...
//
if (reportreq.OwnerId.HasValue)
{
shopsSales = (from sale in ctn.ShopSales
where sale.Shop.OwnerId == reportreq.OwnerId
&& sale.DateSold >= reportreq.FromDate && sale.DateSold <= reportreq.ToDate
select sale).ToList();
}

if (!string.IsNullOrEmpty(reportreq.ShopTypeCode))
{
shopsSales = (from sale in ctn.ShopSales
where sale.Shop.ShopTypeCode.ToUpper().Contains(reportreq.ShopTypeCode.ToUpper())
&& sale.DateSold >= reportreq.FromDate && sale.DateSold <= reportreq.ToDate
select sale).ToList();
}



return shopsSales;
}

您可以看到,此方法仅在未选择过滤器的情况下才查询特定日期之间的销售表。

我坚持的是,用户可以选择多个过滤器 - 例如他们可能会选择一个 regionId 和一个 ShopTypeCode,所以我不想为每个 if 过滤器查询 ctn.ShopSales,因为如果选择了多个,它会清除以前检索到的值。

有没有人对如何解决这个问题有任何建议?如果需要更多信息,请询问!

谢谢

最佳答案

当然 - 您不想每次都从头开始构建查询。只需添加额外的 Where 有条件地调用:

var query = ctn.ShopSales.Where(sale => sale.DateSold >= reportreq.FromDate 
&& sale.DateSold <= reportreq.ToDate);
if (reportreq.OwnerId.HasValue)
{
query = query.Where(sale => sale.Shop.OwnerId == reportreq.OwnerId);
}
if (!string.IsNullOrEmpty(reportreq.ShopTypeCode))
{
query = query.Where(sale.Shop.ShopTypeCode.ToUpper()
.Contains(reportreq.ShopTypeCode.ToUpper());
}

var shopSales = query.ToList();

请注意,查询不会执行,直到您在最后一行实现它。

关于c# - 正确过滤 Linq 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12816985/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com