【问题标题】:Get top 3 most popular items c# linq EF获取前 3 个最受欢迎的项目 c# linq EF
【发布时间】:2020-07-09 06:01:27
【问题描述】:
public class OrderItem
{
    [Key]
    public int ItemId { get; set; }
    public int ProductId { get; set; }
    public virtual Product product { get; set; }
    public int Quantity { get; set; }
}
public class Product
{
    [Key]
    public int ProductId { get; set; }
}

这是我的两节课。我想按每个产品的数量选择前 3 个最受欢迎的产品。喜欢:

[ProductTable]
1
2
3
4


[OrderItemTable]
1, 1, 20
2, 2, 10
3, 3, 5
4, 4, 100
5, 3, 25

结果应该是:
4、3、1 或产品列表。
谢谢。

【问题讨论】:

    标签: c# entity-framework linq asp.net-core


    【解决方案1】:

    我确信这绝不是最佳的,但我相信这是你想要的

    context.Set<OrderItem>()
    .GroupBy(x=>x.ProductId)
    .Select(x=>new{ProductId=x.Key, QuantitySum=x.Sum(a=>a.Quantity)})
    .OrderByDescending(x=>x.QuantitySum)
    .Select(x=>x.ProductId)
    .Take(3)
    .ToList();
    

    【讨论】:

      【解决方案2】:

      以下代码已经过测试,运行正常,希望对你有所帮助

      var row = (from x in OrderItem
                 group x by new { x.ProductId } into val
                 select new
                 {
                     val.Key.ProductId,
                     QuantitySum = val.Sum(s => s.Quantity)
                 }).OrderByDescending(i => i.QuantitySum).Take(3);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-01-22
        • 2010-09-20
        • 1970-01-01
        • 1970-01-01
        • 2020-10-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多