【发布时间】:2013-01-10 14:54:08
【问题描述】:
在我朋友的代码中,他有一个List:
List<int> listOfIds = new List<int>();
然后我用AddRange()给它添加了一个int的集合:
listOfIds.AddRange(this._employeeList
.Where(r => r.EmployeeID != null)
.Select(r => r.EmployeeID != null ? r.EmployeeID.Value : 0));
但是,在日志中,它说:
System.IndexOutOfRangeException: Index was outside the bounds of the array.
at System.Collections.Generic.List`1.Enumerator.MoveNext()
at System.Linq.Enumerable.WhereSelectListIterator`2.MoveNext()
at System.Collections.Generic.List`1.InsertRange(Int32 index, IEnumerable`1 collection)
at the method which called the codes above.....
我不确定为什么会这样。我很确定这个错误发生在上面的代码上,但我似乎不明白为什么会出现IndexOutofRangeException。
你能帮我指出导致这种情况的原因吗?
更新:
我错了。我很抱歉。该方法不使用多线程。但是,另一种调用此方法的方法是使用 Parallel.Foreach,这意味着多线程。可能当 _employeeList 被用作 AddRange() 的源时,另一个线程也在修改它。因此,addrange() 不是线程安全的答案是合理的。非常感谢你们。
【问题讨论】:
-
听起来你是在多线程中使用它。
-
试试这个代码:listOfIds.AddRange(this._employeeList .Where(r => r.EmployeeID != null) .Select(r => r.EmployeeID != null ? r.EmployeeID.Value : 0).ToList())
-
您的
Where和Select不匹配。您的EmployeeID永远不能为空,因为您的Where会将其过滤掉。如果 ID 为 null,您真的希望将0添加到您的列表中吗? -
@Roman,ToList() 有什么帮助?
-
试试吧。我的猜测是您使用 LINQ 查询而不是收集数据。当您调用 .ToList() 查询时只执行一次,而不是每次都使用 .Next() (AddRange 与 IEnumerable 一起使用)
标签: c# linq list indexoutofboundsexception