LINQ to SQL: streamline summation operation

I have a table where I need to arrange the result set by the sum of a numeric column according to the group by clause.

For example, a table has a seller ID, order number, and order value. I want to get the top 10 top managers by the number of accumulated orders.

New to SQL and LINQ, so any advice would be appreciated!

+3
source share
2 answers
var results = context.Sales.GroupBy(s => s.SalesPersonID)
                           .Select(g => new {
                                              SalesPersonID = g.Key, 
                                              Sales = g.Sum(s => s.OrderValue) 
                                             })
                           .OrderByDescending(r => r.Sales)
                           .Take(10);
+7
source

Something like that:

var orders = new[]
{
    new Order { SalesPersonId = 1, OrderNumber = 1, OrderValue = 1 },
    new Order { SalesPersonId = 1, OrderNumber = 2, OrderValue = 2 },
    new Order { SalesPersonId = 2, OrderNumber = 2, OrderValue = 2 },
};

var topSalesMen = orders
    .GroupBy(arg => arg.SalesPersonId)
    .Select(arg => new { SalesPersonId = arg.Key, TotalOrderValue = arg.Sum(x => x.OrderValue) })
    .OrderByDescending(arg => arg.TotalOrderValue)
    .Take(10)
    .ToList();
+2
source

All Articles