每当我尝试打开页面时,我总是收到此“ ArgumentOutOfRange异常所需的非负数,参数名称:index”,但我似乎无法弄清楚负数出现在何处/如何出现。谢谢大家!!

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));


当代码读取“ upcomingMonths”变量时,出现异常。

堆栈跟踪:

[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

最佳答案

根据清单的文档标题

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


因此,我认为月份不包含“当前月份”。
在调用months.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));

09-05 16:07