簡體   English   中英

EF:.Distinct()和.GroupBy正在撤消我的過濾

[英]EF: .Distinct() and .GroupBy are undoing my filtering

我在實體框架中有一個非常簡單的實體層次結構:

-Order
   -Customer
       - Name
   -ProductOrder
       - Quantity
       - Product
           - Name
           - Price

我想編寫一個查詢來獲取執行更昂貴訂單的TOP 5客戶。

該查詢為我提供了這些客戶的ID: [10, 10, 3, 3, 2]

context
  .Orders  
  .Select(o => new { CustomerId = o.CustomerId, Value = o.Products.Sum(p => p.Quantity * p.Product.Price) })  
  .OrderByDescending(x => x.Value)
  .Select(x=> x.CustomerId)
  .Take(5)
  .ToArray()
  ;

正確,有些客戶似乎是重復的,因為下了幾個大訂單。

所以我嘗試添加.Distinct()以避免重復,但是我得到了: [1, 2, 3, 4 ,5]

context
  .Orders
  .Select(o => new { CustomerId = o.CustomerId, Value = o.Products.Sum(p => p.Quantity * p.Product.Price) })
  .OrderByDescending(x => x.Value)
  .Select(x=> x.CustomerId)
  .Distinct()
  .Take(5)
  .ToArray()
  ;

導致所有先前的查詢無用。 .GroupBy

如何使用Entity Framework進行查詢?

對項目進行分組或獲取不同的項目集是一種不維持排序的操作。 在訂購數據之前 ,您需要過濾掉不需要的物品,以便堅持應用您的訂購。

您說您想要擁有前5名最大訂單的客戶,但又不希望重復任何客戶一次。 因此,您真正想要的是最大訂單中的前五名客戶。 這是一種方法:

context
  .Orders  
  .Select(o => new { Customer = o.Customer, Value = o.Products.Sum(p => p.Quantity * p.Product.Price) }) 
  .GroupBy(o => x.Customer)
  .Select(o => new { Customer = o.Key, MaxValue = o.Select(a => a.Value).Max() })
  .OrderByDescending(x => x.MaxValue)
  .Select(x => x.Customer)
  .Take(5)
  .ToArray()
  ;

.ToArray()之前的.ToArray().ToList() .Distinct()應該可以解決問題!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM