I've been optimizing some badly written LINQ queries. I used to iterate over an IQueryable "Items" which was causing the queryable to go to list and slow things down a bit (return all records). I ended up with this code which was noticeably faster:
IQueryable<InventoryItem> Items;
Items = from m in _context.Inventory.Where(m => m.Removed == 0)
select m;
// various filtering happens...
int ItemsCount = await Items.CountAsync();
int TotalQTY = await Items.SumAsync(s=>s.IntegerQuantity);
decimal TotalPrice = await Items.SumAsync(s => s.IntegerQuantity * s.ApproximateCost);
InventoryTotals inventoryTotals = new()
{
TotalQuantity = TotalQTY,
NumberOfItems = ItemsCount,
TotalApproximatePrice = TotalPrice
};
My question is how to combine those three LINQ statements, and if I do, will it be faster? 3 times the speed?
You can try doing the sums in one query using GoupBy
:
var results = Items.GroupBy(s => 1)
.Select(g => new InventoryTotals {
NumberOfItems = g.Count(),
TotalQuantity = g.Sum(s=>s.IntegerQuantity),
TotalApproximatePrice = g.Sum(s => s.IntegerQuantity * s.ApproximateCost)
})
.First();