问题描述
代码是:
_currentTime = UnixTimestamps.RoundTimestamp1(CsvLastLineAggTimestamp(cryptoPair,"agg"));
_tempAgg = File.ReadAllLines("agg" + @cryptoPair + ".csv")
.Select(v => AggTradesClass.FromCsv(v)).ToList();
_nextFiveInterval = UnixTimestamps.RoundTimestamp1(_tempAgg[0].T) + 60000;
_timeFiveInterval = _nextFiveInterval - 60000;
while (_nextFiveInterval <= _currentTime)
{
open = _tempAgg.Where(itm => itm.T >= _timeFiveInterval).First().p;
close = _tempAgg.Where(itm => itm.T < _nextFiveInterval).Last().p;
high = _tempAgg.Where(itm => itm.T >= _timeFiveInterval).Where(itm => itm.T < _nextFiveInterval).Max(itm => itm.p);
low = _tempAgg.Where(itm => itm.T >= _timeFiveInterval).Where(itm => itm.T < _nextFiveInterval).Min(itm => itm.p);
_tempOHLC.Add(new OHLC() { timestamp = _timeFiveInterval });
foreach (var itm in _tempOHLC.Where(item => item.timestamp == _timeFiveInterval))
{
itm.high = high;
itm.low = low;
itm.open = open;
itm.close = close;
}
_nextFiveInterval += 60000;
_timeFiveInterval += 60000;
}
所以这条线
close = _tempAgg.Where(itm => itm.T < _nextFiveInterval).Last().p;
没有任何问题,但在似乎是 while 循环的最后一次迭代中的 high = _tempAgg.Where(itm => itm.T >= _timeFiveInterval).Where(itm => itm.T < _nextFiveInterval).Max(itm => itm.p);
下方的行引发错误:
Message=Sequence 不包含任何元素 Source=System.Core StackTrace: at System.Linq.Enumerable.Max(IEnumerable`1 source) at System.Linq.Enumerable.Max[TSource](IEnumerable1 source,Func2 selector ) 在方法...
解决方法
错误说明了一切。没有与您的查询匹配的元素。所以没有像 itm.T >= _timeFiveInterval 和 itm => itm.T
,让我们实现这一点,而不是一遍又一遍地重复这个查询:
while (_nextFiveInterval <= _currentTime)
{
var c = _tempAgg.Where(itm => itm.T >= _timeFiveInterval && itm.T < _nextFiveInterval)
.Select(item => item.p)
.ToArray();
if(!c.Any()) //no elements
continue;
open = c.First();
close = c.Last();
high = c.Max();
low = c.Min();
它现在实际上是可读的! :)