How to get the top 5 items in the database depending on the availability of a special field?

Using the Ado.Net Entity framework, I try to get the "top 3" elements in the table depending on the number of times that they appear in the table.

For instance:

Table: basket_to_product_id | basket_id | product_id

I want to see how many times product_id appears, and would like to return the most popular 3 product_ids.

I am stuck in:

List<BasketToProduct> btplist = entities.BasketToProduct. ..........?
+3
source share
3 answers

Something like this should work (of course, I don't know the real names of your properties):

IEnumerable<int> top3ProductIds = (from btp in entities.BasketToProduct
                                   group btp by btp.ProductId into g
                                   orderby g.Count() descending
                                   select g.Key).Take(3);
+1
source

You can try to use the LINQ query in the table.

0

:

var query = entities.BasketToProduct
                         .GroupBy(btp => btp.ProductID)
                         .Select(g => ProductID = g.Key, Count = g.Count())
                         .OrderBy(g => g.Count)
                         .Take(3);

He will give you the top three ProductIDsand related calculations.

0
source

Source: https://habr.com/ru/post/1756549/


All Articles