在linq查询里面的Count(),如何避免性能问题?

时间:2014-06-24 01:02:25

标签: linq

我有这个linq声明,我面临一些严重的性能问题。我相信问题在于我在代码中间的.Count()调用。

var products = from product in pm_products
                       join price in GetResellers().Where(x => x.Price != 0) on product.Id equals price.PM_Price.Product_Id into productPrices
                       let minprice = productPrices.Min(x => x.Price)
                       let maxprice = productPrices.Max(x => x.Price)
                       let difference = ((double)maxprice - (double)minprice)/(double)minprice * 100
                       let number = productPrices.Count()
                       let success = productPrices.Where(x => x.Status == PriceStatus.OKAY).Count()
                       let unknown = productPrices.Where(x => x.Status == PriceStatus.NONE).Count()
                       let fail = productPrices.Where(x => x.Status == PriceStatus.FAIL).Count()
                       select new Product
                       {
                           PM_Product = product,
                           BestPrice = minprice,
                           WorstPrice = maxprice,
                           Fail = fail,
                           Number = number,
                           Success = success,
                           Unknown = unknown,
                           Difference = difference
                       };

我已经读过Count()执行查询,但我只希望它执行一次。如何根据我的构造实现这一目标?

1 个答案:

答案 0 :(得分:-1)

你可以带来基本的收藏,然后在内存中进行,也可以帮助他们提高性能。像这样:

let prodPrices = productPrices.Select(pp=>new {pp.Id, pp.Status})

然后将其包含在最终select中,您可以从内存中获取计数