如何使用LINQ按产品组获得最畅销的产品

时间:2019-06-24 20:47:20

标签: c# asp.net-mvc linq

我需要使用linq检索每种产品类型中销售额最高的卖方的名称,产品类型和总和,并将列表返回视图。

{  
    public ActionResult Query2()
    {
        // this part gets me everything into one model type 
        List<QueryViewModel> result = db.SaleProducts
            .GroupBy(prod => prod.Type)
            .SelectMany(sale => sale.Select(
                row => new QueryViewModel
                {
                    Seller = row.Sale.User.Name,
                    ProductType = row.Type,
                    Sales = (double)sale.Where(x => x.Sale.UserId == row.Sale.UserId && x.Type.Equals(row.Type)).Sum(price => price.Price)
                }
            )).Distinct().ToList<QueryViewModel>();

        // this gives me the best per product type but i cant get the seller name 
        List<QueryViewModel> filter = (from res in result
                                       group res by res.ProductType into prodGroup
                                       select new QueryViewModel
                                       {
                                           ProductType = prodGroup.Key,
                                           Sales = prodGroup.Max(x => x.Sales)
                                       }).ToList<QueryViewModel>();

        // this is really just to get the seller name at this point 
        List<QueryViewModel> something = (from res in result
                                          join f in filter on res.Sales equals f.Sales
                                          select new QueryViewModel
                                          {
                                              Seller = res.Seller,
                                              ProductType = res.ProductType,
                                              Sales = res.Sales
                                          }).ToList<QueryViewModel>();

        return View(something);
    }
}

它应该返回QueryViewModel的列表(名称,产品类型,总销售额)。

它确实返回了,但是这看起来非常混乱,而且我对LINQ的了解还不足以清除它。

是否有更好的清洁方法来实现所需的输出?

1 个答案:

答案 0 :(得分:0)

第一个分组应按类型和卖方进行。

类似的事情应该可以帮助您:

Quote_Masters.GroupBy(qm => new { qm.OrderTypeId, qm.SalesRepEmployeeId })
    .Select(x => new { Name = x.Key.SalesRepEmployeeId, x.Key.OrderTypeId, Total = x.Sum(qm => qm.Total_Price) })
    .OrderByDescending(x => x.Total).GroupBy(x => x.OrderTypeId).Select(x => x.FirstOrDefault())

只需更改适当的表和字段即可。


编辑:您选择的QueryViewModel将是新的{Name = x.Key.SalesRepEmployeeId,x.Key.OrderTypeId,Total = x.Sum(qm => qm.Total_Price)}