0

I have a table (Items) with records in this format.

Name     | ProductId | Owner
Product1 | 1         | xx
Product2 | 2         | yy
Product1 | 1         | xx
Product3 | 3         | xx
Product3 | 3         | xx
Product3 | 3         | xx
Product4 | 4         | xx
Product2 | 2         | xx
Product5 | 5         | xx

I want to write entity framework query that will return the top 3 products, their names and Count. The result should look like this.

Result
Name: [Product3, Product2, Product1],
Count:[3, 2, 2]

I have checked other answers here on SO but still did not find something close to what i want. Note Name and Count returns a list of the top 3 respectively.

3
  • What about using linq GroupBy? Do you want to use linq? Commented Oct 21, 2017 at 15:23
  • @AryanFirouzyan, yes if returns the expected output Commented Oct 21, 2017 at 15:29
  • @InBetween answer seems ok Commented Oct 21, 2017 at 15:31

2 Answers 2

3

You can try this code

var query = context
            .products
            .GroupBy(p => p.Name)
            .OrderByDescending(g => g.Count())
            .Take(3);

products.Select(p => new
{
    Name = query.Select(g => g.Key).ToList(),
    Count = query.Select(g => g.Count()).ToList(),
})
.FirstOrDefault();

Although I recommend that you get top 3 product with count together from database and then put it in different list, like this :

var products = context.products
            .GroupBy(p => p.Name)
            .OrderByDescending(g => g.Count())
            .Take(3)
            .Select(g => new
            {
                Name = g.Key,
                Count = g.Count()
            })
            .ToList();
List<string> names = products.Select(p => p.Name).ToList();
List<int> counts = products.Select(p => p.Count).ToList();
Sign up to request clarification or add additional context in comments.

3 Comments

You should be ordering by descending order, otherwise you are taking the bottom 3 products.
@InBetween you're right, thanks. I edited the answer
Thank you @Arvin, just what i was looking for.
2

The following should work:

products.GroupBy(p => p.ProductId)
        .OrderByDescending(g => g.Count())
        .Take(3);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.