是否可以使用较少的foreach循环编写以下代码?
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();
}
}
我不知道这是否可行,但我希望在那里使用更少的foreach循环来实现相同的功能。
答案 0 :(得分:3)
如果没有关于这个问题的更多数据,有点难以看到你想要的东西......
但我怀疑你可以这样做某事(完全未经测试)......
但实际上,除非你遇到某种性能问题,否则我不会担心它。你拥有的代码比这更容易调试 - 我怀疑无论如何,性能会有太大差异。根据_db的不同,可能会导致在数据库上执行汇总操作,从而提供更好的性能(由于将LINQ转换为SQL),但这取决于很多其他的东西......
foreach 循环本质上并不坏。没有理由不使用它们。我们都使用Linq的风格和代码简洁的原因,但最后,如果系统正在处理内存中的数据,编译器将最终或多或少地优化所有这些循环/求和的东西同样的方式。
var pensInShed = _db.Pens.Where(w => w.ShedId == selectedShedGuid).Select(s => s.PensGuid);
foreach(var penId in pensInShed)
{
var shedTotal =
_db.DailyConsumptionPens
.Where(w => w.PenId == penId && w.Timestamp == ConvertedDate)
.Sum(x =>
_db.ConsumptionUnits
.Where(w =>
w.DailyConsumptionId == x.ConsumptionPenGuid)
.Sum(xx => xx.UnitNETWeight * xx.UnitsUsed)
);
var pensToUpdate = _db.DailyConsumptionPens
.Where(w => w.PenId == penId && w.Timestamp == ConvertedDate)
.ToList();
foreach(var pen in pensToUpdate)
{
pen.TotalShedUsage = shedTotal;
_db.SaveChanges();
}
}