如何在这种特殊情况下简化foreach?
foreach (var product in Produkty.Model)
{
product.Price0 += Math.Round((product.Price0 ?? 0) * (countValue / oldCountValue), accuracyValue);
product.Price1 += Math.Round((product.Price1 ?? 0) * (countValue / oldCountValue), accuracyValue);
product.Price2 += Math.Round((product.Price2 ?? 0) * (countValue / oldCountValue), accuracyValue);
product.Price3 += Math.Round((product.Price3 ?? 0) * (countValue / oldCountValue), accuracyValue);
product.Price4 += Math.Round((product.Price4 ?? 0) * (countValue / oldCountValue), accuracyValue);
product.Price5 += Math.Round((product.Price5 ?? 0) * (countValue / oldCountValue), accuracyValue);
product.Price6 += Math.Round((product.Price6 ?? 0) * (countValue / oldCountValue), accuracyValue);
product.Price7 += Math.Round((product.Price7 ?? 0) * (countValue / oldCountValue), accuracyValue);
product.Price8 += Math.Round((product.Price8 ?? 0) * (countValue / oldCountValue), accuracyValue);
product.Price9 += Math.Round((product.Price9 ?? 0) * (countValue / oldCountValue), accuracyValue);
}
答案 0 :(得分:3)
Func<double?, double> calc =
p => Math.Round((p ?? 0) * (countValue / oldCountValue), accuracyValue);
foreach (var product in Produkty.Model)
{
product.Price0 += calc(product.Price0);
product.Price1 += calc(product.Price1);
// ... rinse and repeat.
}