public static IEnumerable <MaterialBatchViewModel> JoinAutomaticBatches(IEnumerable <MaterialBatchViewModel> source, AmountProcessor processor) { var targetList = new List <MaterialBatchViewModel>(); foreach (var batch in source.OrderBy(i => i.MaterialId)) { if (batch.AutomaticBatches && (targetList.LastOrDefault()?.MaterialId == batch.MaterialId)) { var joined = targetList.Last(); joined.BatchNumber = null; joined.Id = null; var sum = processor.Add(processor.ToAmount(batch.Volume, batch.UnitName), processor.ToAmount(joined.Volume, joined.UnitName)); joined.UnitName = sum.Unit.Symbol; joined.Volume = sum.Value; continue; } targetList.Add(batch); } return(targetList); }