在以下代码中,我收到了以下错误。
mscorlib.dll中出现未处理的“System.ArgumentOutOfRangeException”类型异常
其他信息:指数超出范围。必须是非负数且小于集合的大小。
这是代码:
public ProcessInformation GetMaxRunTimeForApplicationsBetween(DateTime StartingTime, DateTime EndingTime)
{
//Filter Based on Timer
List<ProcessInformation> filterList = new List<ProcessInformation>();
foreach (HarvestApp.ProcessInformation item in this.ProcessList)
{
if (item.started_at.CompareTo(StartingTime) >= 0 && item.ended_at.CompareTo(EndingTime) <= 0)
{
filterList.Add(item);
}
}
//Count Max Occurrence of Application
List<int> countApplicationList = new List<int>();
List<string> applicationNameList = new List<string>();
foreach (HarvestApp.ProcessInformation item in filterList)
{
if (applicationNameList.Contains(item.name))
{
countApplicationList[applicationNameList.IndexOf(item.name)]++;
}
else
{
applicationNameList.Add(item.name);
countApplicationList.Add(1);
}
}
//if (countApplicationList.Count == 0)
//{
// throw new InvalidOperationException("Empty list");
//}
int max = int.MinValue;
foreach (int item in countApplicationList)
{
if (item > max)
{
max = item;
}
}
//Return corresponding ProcessInformation Class of applicationNameList
return filterList[filterList.FindIndex(delegate
(ProcessInformation proc)
{
return proc.name.Equals(applicationNameList[countApplicationList.IndexOf(max)], StringComparison.Ordinal);
})];
}
答案 0 :(得分:2)
我认为错误行在这里:
return filterList[filterList.FindIndex(delegate(ProcessInformation proc)
{
return proc.name.Equals(applicationNameList[countApplicationList.IndexOf(max)], StringComparison.Ordinal);
})];
因为当您找不到索引时List<T>.FindIndex
可以返回-1
。
相反,您应该在使用之前测试索引是否小于0,这表示存在错误:
int result = filterList.FindIndex(delegate(ProcessInformation proc)
{
return proc.name.Equals(applicationNameList[countApplicationList.IndexOf(max)], StringComparison.Ordinal);
});
if(result < 0) throw new Exception("Cant't Find ProcessInformation");
return filterList[result];
答案 1 :(得分:0)
问题在于:
if (applicationNameList.Contains(item.name))
{
**countApplicationList[applicationNameList.IndexOf(item.name)]++;**
}
应该是这样的
if (applicationNameList.Contains(item.name) && countApplicationList.Count > applicationNameList.IndexOf(item.name))
{
countApplicationList[applicationNameList.IndexOf(item.name)]++;
}