Давайте извлекать Price
метод:
// Prices: Key - distance (in km); Value - price
private static Dictionary<decimal, decimal> defaultPrices =
new Dictionary<decimal, decimal>() {
{ 100m, 1.00m},
{ 50m, 1.25m},
{ 10m, 1.50m},
{ 0m, 2.00m},
};
private static decimal Price(decimal distance,
IDictionary<decimal, decimal> policy = null) {
// if no price policy provided, use default one
if (null == policy)
policy = defaultPrices;
decimal result = 0.00m;
while (distance > policy.Keys.Min()) {
var pair = policy
.Where(item => distance > item.Key)
.OrderByDescending(item => item.Key)
.First();
result += (distance - pair.Key) * pair.Value;
distance = pair.Key;
}
return result;
}
Тогда мы можем легко использовать его, например, давайте вычислим tolal
сумму:
List<decimal> distances = ...
// Alas, we can't Sum() decimals, let's Aggregate them
decimal total = distances.Aggregate(0.00m, (s, d) => s + Price(d));
Демо:
decimal[] tests = new decimal[] {
8, 35, 60, 120
};
string report = string.Join(Environment.NewLine, tests
.Select(d => $"{d,3} km costs {Price(d),6} $"));
Console.WriteLine(report);
string reportTotal = $"Total: {tests.Aggregate(0.00m, (s, d) => s + Price(d))} $";
Console.WriteLine();
Console.WriteLine(reportTotal);
Результат:
8 km costs 16.00 $
35 km costs 57.50 $
60 km costs 92.50 $
120 km costs 162.50 $
Total: 328.50 $
Обратите внимание, что 60
км стоит 10 * 1.25$ + 40 * 1.50$ + 10 * 2.00$ == 92.50$
, а не 86.25$
как в вопросе.