我正在创建一个 C# WPF 应用程序,让用户接受订单(想想餐厅/酒吧)。
为简单起见,我将订单限制为对单个商品的简单购买(您可以购买多个商品,例如购买 4 杯啤酒)。每个购买都记录为一个 Purchase 对象:
class Purchase
{
public int id {get;set;}
public DateTime time {get;set;}
public double price {get;set;}
public int quantity {get;set;}
}
并且每次购买都会添加到 DataTable 中。
我想在给定时间内获得 3 个最多购买和 3 个最少购买的商品,但我无法为此编写合适的查询。
到目前为止,我所拥有的是这个,但它不起作用:
public List<int> GetMostBought()
{
DateTime lastMinute = DateTime.UtcNow.Add(new TimeSpan(0, -1, 0)); //one minute ago
int howMany = 3; // how many items to get.
var query =
(from p in purchases.AsEnumerable()
where p.Field<DateTime>("time")>= lastMinute //purchases made less than a minute ago
select new { Product = p, Quantity = p.Field<int>("quantity") } into productQty
group productQty by productQty.Product into pg
let totalQuantity = pg.Sum(prod => prod.Quantity)
orderby totalQuantity descending
select pg.Key).Take(howMany);
List<int> mostBoughtIDs = new List<int>();
foreach (DataRow dr in query)
{
mostBoughtIDs.Add(Int32.Parse(dr[0].ToString()));
}
return mostBoughtIDs;
有任何想法吗?