demo.b
demo.b

Reputation: 3449

How do i write this query in entity-framework

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.

Upvotes: 0

Views: 67

Answers (2)

Kahbazi
Kahbazi

Reputation: 15015

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

Upvotes: 3

InBetween
InBetween

Reputation: 32790

The following should work:

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

Upvotes: 2

Related Questions