ArgumentOutOfRangeException参数名称:索引

时间:2017-11-13 15:33:46

标签: c# linq

我一直得到这个' ArgumentOutOfRange异常非负数,参数名称:索引',每当我尝试打开页面时,我似乎无法弄清楚在哪里/如何准确负数正在出现。提前谢谢大家!!

var months = data.OrderBy(x => x.ApproximatedStartDate).Select(x => x.Month).Distinct((x, y) => x == y).OrderBy(x => x).ToList();
var upcomingMonths = months.GetRange(months.IndexOf(DateTime.Today.Month), months.Count - months.IndexOf(DateTime.Today.Month));

当代码读取“即将到来的月份”时,我会收到异常。变量

堆栈跟踪:

[ArgumentOutOfRangeException: Non-negative number required. Parameter name: index]
System.ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument argument, ExceptionResource resource) +72
System.Collections.Generic.List`1.GetRange(Int32 index, Int32 count) +4951591
InitializeChartBC() 
Page_Load(Object sender, EventArgs e)
System.Web.UI.Control.OnLoad(EventArgs e) +103
System.Web.UI.Control.LoadRecursive() +68
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3811

1 个答案:

答案 0 :(得分:3)

根据列表的文档标题

// Exceptions:
//   T:System.ArgumentOutOfRangeException:
//     index is less than 0.-or-count is less than 0.

所以我认为几个月并不包含当月。 在您拨打这几个月之前。 GetRange 检查它是否包含当前月份,然后调用 GetRange

var months = data.OrderBy(x => x.ApproximatedStartDate).Select(x => x.Month).Distinct((x, y) => x == y).OrderBy(x => x).ToList();
 //Anyone corrent me as the list is converted to **.ToList** it wont throw null error I feel
List<T> upcomingMonths = null;  //Where T is the type of the list
if(months.IndexOf(DateTime.Today.Month)>=0)
      upcomingMonths = months.GetRange(months.IndexOf(DateTime.Today.Month), months.Count - months.IndexOf(DateTime.Today.Month));