[英]Index out of range error
我的项目中有以下方法:
public double CalculateDailyProjectMaxPumpSpm(DateTime date, string start = null, string end = null)
{
Log("Calculating Daily Pump stroke Max...");
var spm = new List<double>();
if (start == null)
{
for (var i = 0; i < _pumpOneSpm.Count; i++)
{
if (_date[i].Equals(date))
{
spm.Add(_pumpOneSpm[i]);
spm.Add(_pumpTwoSpm[i]);
}
}
}
else
{
for (var i = 0; i < _pumpOneSpm.Count; i++)
{
if (_date[i].Equals(date) &&
DateTime.Compare(_time[i], DateTime.Parse(start)) > 0 &&
DateTime.Compare(_time[i], DateTime.Parse(end)) < 0)
{
spm.Add(_pumpOneSpm[i]);
spm.Add(_pumpTwoSpm[i]);
}
}
}
return _dailyProjectMaxSpm = Math.Round(spm.Max(), 2, MidpointRounding.AwayFromZero);
}
我试图让这个方法看起来不那么笨拙。 我试过了:
public double CalculateDailyProjectMaxPumpSpm(DateTime date, string start = null, string end = null)
{
Log("Calculating Daily Pump stroke Max...");
var spm = start == null ? _pumpOneSpm.Concat(_pumpTwoSpm).Where((t, i) => _date[i].Equals(date)).ToList()
: _pumpOneSpm.Concat(_pumpTwoSpm).Where((t, i) => _date[i].Equals(date) &&
DateTime.Compare(_time[i], DateTime.Parse(start)) > 0 &&
DateTime.Compare(_time[i], DateTime.Parse(end)) < 0).ToList();
_dailyProjectMaxSpm = Math.Round(spm.Max(), 2, MidpointRounding.AwayFromZero);
return _dailyProjectMaxSpm;
}
但是当我运行该程序时,我的Index out of range. Must be non-negative and less than the size of the collection. Parameter name: index
Index out of range. Must be non-negative and less than the size of the collection. Parameter name: index
Index out of range. Must be non-negative and less than the size of the collection. Parameter name: index
错误。 现在,我不在乎将元素添加到新列表的顺序,只要符合条件,就会添加它们。 任何人都可以帮我解决这个错误吗? 谢谢。
UPDATE
_date
是从数据库中提取的日期列表, _time
是从同一数据库中提取的时间戳列表。 带_
所有变量都是从数据库中提取的列表。 每个列表的Count
将始终等于彼此列表的Count
。
在原始方法中, i
的范围从0
到_pumpOneSpm.Count
但现在从0
到_pumpOneSpm.Count + _pumpTwoSpm.Count
以下结果列出了_pumpOneSpm.Count + _pumpTwoSpm.Count
项:
_pumpOneSpm.Concat(_pumpTwoSpm).Where((t, i) => _date[i]
而且我看不到LINQ模拟比使用for
循环的第一个方法示例更清晰。
就像sil说的那样,你要连接两个列表,从而得到一个索引范围更大的列表。 这个解决方案如何使用Enumerable.Range()生成索引,然后使用两个谓词的组合版本进行过滤,最后使用SelectMany()展开列表:
public double CalculateDailyProjectMaxPumpSpm(DateTime date, string start = null, string end = null)
{
Log("Calculating Daily Pump stroke Max...");
var spm = Enumerable
.Range(0, _pumpOneSpm.Count)
.Where(x => _date[x].Equals(date) &&
(start == null ||
(DateTime.Compare(_time[x], DateTime.Parse(start)) > 0 &&
DateTime.Compare(_time[x], DateTime.Parse(end)) < 0)))
.SelectMany(x => new [] { _pumpOneSpm[x], _pumpTwoSpm[x] });
return _dailyProjectMaxSpm = Math.Round(spm.Max(), 2, MidpointRounding.AwayFromZero);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.