正确过滤Linq查询

时间:2012-10-10 10:15:54

标签: c# linq linq-to-entities linq-query-syntax

我有这个查询从一堆商店检索销售,并将它们作为列表返回。在我的报告请求屏幕上,用户可以按多个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,因为如果选择了多个,它将​​清除以前检索的值。

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

由于

1 个答案:

答案 0 :(得分:4)

当然 - 您不希望每次都从头开始构建查询。只需有条件地添加额外的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();

请注意,在最后一行中实现查询之前,查询不会执行