在C#中的属性之后简化foreach迭代

时间:2017-03-07 19:26:14

标签: c#

如何在这种特殊情况下简化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);
}

1 个答案:

答案 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.
}