For each part, I want to summarize the total onhand and allocated in the warehouse and on order in order lines.
I'm working with a simplified version in LINQPad:
void Main()
{
var partQuantities = (
from part in Parts()
join orderLine in OrderLines()
on part.PartID equals orderLine.PartID
into orderLineLeftJoin
from orderLine in orderLineLeftJoin.DefaultIfEmpty()
join warehouse in Warehouses()
on part.PartID equals warehouse.PartID
into warehouseLeftJoin
from warehouse in warehouseLeftJoin.DefaultIfEmpty()
group new { warehouse, orderLine } by part into partQtys
/*
select partQtys
// */
// /*
select new
{
partQtys.Key.PartID,
OnHandQty = partQtys.Sum(partQty => partQty.warehouse.OnHandQty),
AllocatedQty = partQtys.Sum(partQty => partQty.warehouse.AllocatedQty),
OrderQty = partQtys.Sum(partQty => partQty.orderLine.OrderQty)
}
// */
).Dump();
}
class Part { public string PartID; }
private Part[] Parts() { return new Part[] {new Part { PartID = "PartA" },new Part { PartID = "PartB" },new Part { PartID = "PartC" },new Part { PartID = "PartD" },new Part { PartID = "PartE" },new Part { PartID = "PartF" }}; }
class Warehouse { public string WarehouseID; public string PartID; public int OnHandQty; public int AllocatedQty; }
private Warehouse[] Warehouses() { return new Warehouse[] {new Warehouse { WarehouseID = "Whse1", PartID = "PartA", OnHandQty =101, AllocatedQty = 21 },new Warehouse { WarehouseID = "Whse1", PartID = "PartB", OnHandQty =102, AllocatedQty = 22 },new Warehouse { WarehouseID = "Whse1", PartID = "PartC", OnHandQty =103, AllocatedQty = 23 },new Warehouse { WarehouseID = "Whse1", PartID = "PartD", OnHandQty =104, AllocatedQty = 24 },new Warehouse { WarehouseID = "Whse2", PartID = "PartC", OnHandQty =105, AllocatedQty = 25 },new Warehouse { WarehouseID = "Whse2", PartID = "PartD", OnHandQty =106, AllocatedQty = 26 },new Warehouse { WarehouseID = "Whse2", PartID = "PartE", OnHandQty =107, AllocatedQty = 27 },new Warehouse { WarehouseID = "Whse2", PartID = "PartF", OnHandQty =108, AllocatedQty = 28 }}; }
class OrderLine { public string OrderID; public string PartID; public int OrderQty; }
private OrderLine[] OrderLines() { return new OrderLine[] {new OrderLine { OrderID = "Order1", PartID = "PartB", OrderQty = 71 }, new OrderLine { OrderID = "Order1", PartID = "PartF", OrderQty = 72 },new OrderLine { OrderID = "Order2", PartID = "PartD", OrderQty = 73 }, new OrderLine { OrderID = "Order2", PartID = "PartF", OrderQty = 74 }}; }
But this gets a NullReferenceException because not all parts have both warehouse stock and orders.
EDIT: I'd already ruled out Gilad's null propagating operator because the unsimplified version is an Expression Tree Lambda and I get a compile error. Though this would work in LinqPad.
How do I summarize this data from two tables?