简体   繁体   中英

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.

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

The following should work:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM