Get top 3 most popular items c# linq EF

Viewed 597
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; }
}

Here is two my classes. I want to select top 3 most popular products by count of Quantity of each Product. Like:

[ProductTable]
1
2
3
4


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

And the result should be:
4, 3, 1 or list of Products.
Thank you.

2 Answers

I am sure that this is by no way optimal, but I believe it is what you want

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();

The following code has been tested and is working properly,I hope help you

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);
Related