public void Merge(Int32 materialIdToKeep, Int32[] materialIdToDelete) { foreach (var id in materialIdToDelete) { //Get all the ProductMaterial whith materialIdToDelete var _materialwithProductsDelete = _materialRepository.GetMaterialsWithProducts(id); var _productMaterialDelete = _materialwithProductsDelete.Select(p => p.ProductMaterials).ToList(); for (int i = 0; i < _productMaterialDelete.Count(); i++) { var collectionOfMaterial = _productMaterialDelete[i]; foreach (var prMaterial in collectionOfMaterial) { var _materialwithProductsToKeep = _materialRepository.GetMaterialsWithProducts(materialIdToKeep).FirstOrDefault(); var _actualProductMaterial = _materialwithProductsToKeep.ProductMaterials.FirstOrDefault(); //Need to update the quentity only and then delet the unused product details _actualProductMaterial.Quantity += prMaterial.Quantity; _materialRepository.UpdateProductMaterials(_actualProductMaterial); _materialRepository.DeleteProductMaterials(prMaterial.ProductMaterialId); _materialRepository.Delete(prMaterial.MaterialId); if (collectionOfMaterial.Count() <= 0) { break; } } } //} //Delete the Material (I would prefer to mark delte but this desing is like this so keep it as it is) } }