Is it possible to write the following code with less foreach loops?
var pensInShed = _db.Pens.Where(w => w.ShedId == selectedShedGuid).Select(s => s.PensGuid);
foreach(var penId in pensInShed)
{
var pensInWeanedShed = _db.DailyConsumptionPens.Where(w => w.PenId == penId && w.Timestamp == ConvertedDate).Select(s => s.ConsumptionPenGuid);
foreach(var consumptionGuid in pensInWeanedShed)
{
var matchedUnits = _db.ConsumptionUnits.Where(w => w.DailyConsumptionId == consumptionGuid);
foreach(var unit in matchedUnits)
{
var unitLine = unit.UnitNETWeight * unit.UnitsUsed;
shedTotal += unitLine;
}
}
var pensToUpdate = _db.DailyConsumptionPens.Where(w => w.PenId == penId && w.Timestamp == ConvertedDate).ToList();
foreach(var pen in pensToUpdate)
{
pen.TotalShedUsage = shedTotal;
_db.SaveChanges();
}
}
I do not know if this is possible but I am wanting to have the same functionality with less foreach loops in there.