Home > Back-end >  LINQ: How to find most popular item from column
LINQ: How to find most popular item from column

Time:12-22

I want to find which item is most popular in my Orders table with the 'ItemTitle' column.

ItemTitle has the following:

  • King burger
  • Hawaiian
  • Classico Italiano
  • Tiramisu
  • King burger
  • King burger
  • Classico Italiano
  • Classico Italiano
  • King burger

What is the best LINQ query to find which item is most popular? Thank you!

Here is my try:

 return _DbContext.Orders.GroupBy(x => x.ItemTitle).Where(g => g.Count() > 1).OrderByDescending(g => g.Count()).Select(g => g.Key).Take(1);

It's working, however, it has a bug. The bug is Orders has Quantity column. ex: In the list below there are 4 King Burger's x 1 - Quantity. If the Tiramisu has x 10 - Quantity, Now the most popular item should be the tiramisu.

CodePudding user response:

If you don't care about ties, then you can use this:

var query =
    orders
        .GroupBy(x => x.ItemTitle, x => x.Quantity)
        .Select(x => new { ItemTitle = x.Key, Quantity = x.Sum() })
        .OrderByDescending(x => x.Quantity)
        .Take(1)
        .SingleOrDefault();

Otherwise, if tracking ties are important, then this works:

var querySupportingTies =
    orders
        .GroupBy(x => x.ItemTitle, x => x.Quantity)
        .Select(x => new { ItemTitle = x.Key, Quantity = x.Sum() })
        .ToLookup(x => x.Quantity, x => x.ItemTitle)
        .OrderByDescending(x => x.Key)
        .Select(x => new
        {
            Quantity = x.Key,
            ItemTitles = x.ToArray()
        })
        .Take(1)
        .SingleOrDefault();
  • Related