Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Linq GroupBy, get list of a column in each group

Tags:

c#

sql

linq

I need to write a query to get all the shipping costs of sales, and compare it against an estimated shipping cost. Here is my query:

var sales = (from sale in db.Sales
             where sale.DateOfSale > startDate && sale.DateOfSale < endDate
             group sale by new {sale.ItemID, sale.EstimatedShipping} into g
             select new
             {
                 ItemID = g.Key.ItemID
                 Estimate = g.Key.EstimatedShipping
                 ActualShipCosts = (from gSales in g select gSales.ActualShipping)
             }).ToList();

It seems that doing anything with the group that isn't getting the group by keys or doing g.Count() makes the query run terribly slow, I can't get this query to finish without timing out. Is there anything I can do to help performance here?

like image 502
IrkenInvader Avatar asked Dec 05 '25 03:12

IrkenInvader


1 Answers

You can try performing the ActualShipping selection while you are building the result set:

var sales = db.Sales
    .Where(sale => sale.DateOfSale > startDate && sale.DateOfSale < endDate)
    .GroupBy(
        sale => new {sale.ItemID, sale.EstimatedShipping},
        sale => sale.ActualShipping)
    .ToList();

Not sure, but it could prevent additional enumeration.

like image 146
galenus Avatar answered Dec 07 '25 15:12

galenus