我认为您需要从抽象您的时间序列数字列表开始。似乎每组计算都必须以不同的方式遍历列表。
interface IMyList<T>
{
void SetList(IList<T> series);
bool IsDone();
T GetOperand1();
T GetOperand2();
T Calculate(T op1, T op2);
void SetResult(T result);
void Next();
Dictionary<int, IList<T>> GetResults();
}
当您在每个类中实现每个 IMyList 时,您将在类中构建应该如何遍历列表的确切方式。我已经实现了你的第一个例子。还要注意我没有使用递归。对于每种类型的遍历和计算,您可以创建一个像这样的类:
public class Ratio : IMyList<double>
{
private Dictionary<int, IList<double>> _results;
private int _currentSeries;
private int _seriesResults;
private int _op1Index;
private int _op2Index;
private bool _bDone;
public Ratio()
{
_op1Index = 0;
_op2Index = 1;
_currentSeries = 0;
_seriesResults = 1;
}
public void SetList(IList<double> series)
{
// the zero entry is the first result set
_results = new Dictionary<int, IList<double>>();
_results.Add(_currentSeries, series);
_results.Add(_seriesResults, new List<double>());
}
public bool IsDone()
{
return _bDone;
}
public double GetOperand1()
{
return _results[_currentSeries][_op1Index];
}
public double GetOperand2()
{
return _results[_currentSeries][_op2Index];
}
public double Calculate(double op1, double op2)
{
return op1 / op2;
}
public void SetResult(double result)
{
_results[_seriesResults].Add(result);
}
public void Next()
{
_op1Index++;
_op2Index++;
if (_op2Index >= _results[_currentSeries].Count())
{
if (_results[_seriesResults].Count == 1)
{
_bDone = true;
}
else
{
_currentSeries++;
_seriesResults++;
_results.Add(_seriesResults, new List<double>());
_op1Index = 0;
_op2Index = 1;
}
}
}
public Dictionary<int, IList<double>> GetResults()
{
return _results;
}
}
要将其付诸实践,代码将是:
List<double> firstList = new List<double>() { 15, 36, -7, 12, 8 };
// the following section could be refactored further by putting the classes
// in a list of IMyList and then looping through it
var rat = new Ratio();
rat.SetList(firstList);
while (!rat.IsDone())
{
double op1 = rat.GetOperand1();
double op2 = rat.GetOperand2();
rat.SetResult(rat.Calculate(op1, op2);
rat.Next();
}
var results = rat.GetResults();