2014-06-24 27 views
0

我有這個linq聲明,我正面臨一些嚴重的性能問題。我相信問題在於我的.Count()調用在代碼中間。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

如果刪除'計數()'會發生什麼得到的計數?你的查詢變得更快了嗎? – dasblinkenlight

+0

好吧,您已經至少有兩次(最小和最大)彙總「productPrices」連接,所以我懷疑Count是否對它負責。 –

+0

是的。它從1600毫秒到32ms – Peter

回答

-1

你可以帶上基本的收藏品,然後在記憶中做,也可能會有助於表現。事情是這樣的:

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

然後將其包含在最終select,你可以從這個內存

+0

真正有用的貢獻只是爲了downvote –