Ниже приведен простой класс, который позволяет устанавливать HighTemps
и LowTemps
.Существует также свойство только для чтения TempRange
, которое использует цикл для вычисления в getter
.Есть ли более элегантный способ сделать это, кроме цикла?Учитывая, что TempRange всегда будет производным от HighTemps
и LowTemps
и что у всех трех будет в основном 7 элементов с индексом, есть ли лучший способ сделать это без цикла для установки значения TempRange
?
using System;
using System.Collections.Generic;
public class Program
{
public class Weather{
public Weather(Dictionary<int,int> highTemps,Dictionary<int,int> lowTemps,Dictionary<int,int> tempRange){
HighTemps = highTemps;
LowTemps = lowTemps;
}
public Dictionary<int,int> HighTemps {get;set;}
public Dictionary<int,int> LowTemps {get;set;}
public Dictionary<int,int> TempRange{
get{
Dictionary<int,int> result = new Dictionary<int,int>();
foreach (KeyValuePair<int, int> pair in HighTemps)
{
result.Add(pair.Key,pair.Value - LowTemps[pair.Key]);
}
return result;
}
}
}
public static void Main(){
Weather temps = new Weather(new Dictionary<int,int>(),new Dictionary<int,int>(),new Dictionary<int,int>());
//add day of week and temp
temps.HighTemps.Add(1, 84);
temps.HighTemps.Add(2, 86);
temps.HighTemps.Add(3, 81);
temps.HighTemps.Add(4, 82);
temps.HighTemps.Add(5, 82);
temps.HighTemps.Add(6, 83);
temps.HighTemps.Add(7, 84);
temps.LowTemps.Add(1, 65);
temps.LowTemps.Add(2, 66);
temps.LowTemps.Add(3, 71);
temps.LowTemps.Add(4, 60);
temps.LowTemps.Add(5, 64);
temps.LowTemps.Add(6, 69);
temps.LowTemps.Add(7, 70);
foreach (KeyValuePair<int, int> pair in temps.TempRange)
{
Console.WriteLine("The range for Day {0} of the week was {1}", pair.Key, pair.Value);
}
}
}
//Output:
The range for Day 1 of the week was 19
The range for Day 2 of the week was 20
The range for Day 3 of the week was 10
The range for Day 4 of the week was 22
The range for Day 5 of the week was 18
The range for Day 6 of the week was 14
The range for Day 7 of the week was 14