private decimal TryFindProductionOrders(IDemandToProvider demand, decimal amount) { var possibleMatchingProductionOrders = _context.ProductionOrders.Where(a => a.ArticleId == demand.ArticleId && a.ProductionOrderWorkSchedule.Any(b => b.ProducingState != ProducingState.Finished)).ToList(); while (amount > 0 && possibleMatchingProductionOrders.Any()) { var earliestProductionOrder = _context.GetEarliestProductionOrder(possibleMatchingProductionOrders); var availableAmountFromProductionOrder = _context.GetAvailableAmountFromProductionOrder(earliestProductionOrder); if (availableAmountFromProductionOrder == 0) { possibleMatchingProductionOrders.Remove(possibleMatchingProductionOrders.Find(a => a.Id == earliestProductionOrder.Id)); continue; } var provider = _context.CreateProviderProductionOrder(demand, earliestProductionOrder, amount >= availableAmountFromProductionOrder ? availableAmountFromProductionOrder : amount); var duetime = _context.GetDueTimeByOrder(demand); if (provider.ProductionOrder.DemandProviderProductionOrders.Count == 1) { provider.ProductionOrder.Duetime = duetime; } else if (provider.ProductionOrder.Duetime > duetime) { provider.ProductionOrder.Duetime = duetime; } _context.AssignProviderToDemand(demand, provider); _context.AssignProductionOrderToDemandProvider(earliestProductionOrder, provider); if (amount > availableAmountFromProductionOrder) { amount -= availableAmountFromProductionOrder; } else { amount = 0; } possibleMatchingProductionOrders.ToList().Remove(earliestProductionOrder); } return(amount); }