[英]FindLastIndex ArgumentOutOfRangeException when parameter count is less than List.Count
I'm puzzled with a problem regarding C# List
, the code below throws ArgumentOutOfRangeException
: 我对C#
List
的问题感到困惑,下面的代码抛出了ArgumentOutOfRangeException
:
List<int> l = new List<int>();
l.Add(1); l.Add(1); l.Add(1); l.Add(1); l.Add(1);
l.Add(1); l.Add(1); l.Add(1); l.Add(1); l.Add(1);
l.Add(1); l.Add(1); l.Add(1); l.Add(1); l.Add(1); // 15 elements
// v <--- From 0
l.FindLastIndex(0, 5, v => v != 1);
// ^ <--- up to 5 elements
As far as I understand the code above, the method will apply the lambda from the element 0 until it reaches 5 elements (element 4), but it throws the ArgumentOutOfRangeException
even if it mustn't according to my understanding of the documentation : 据我所知,上面的代码,该方法将应用元素0中的lambda,直到它达到5个元素(元素4),但它会抛出
ArgumentOutOfRangeException
即使它不能根据我对文档的理解:
ArgumentOutOfRangeException
startIndex
is outside the range of valid indexes for theList<T>
.startIndex
超出了List<T>
的有效索引范围。-or-
-要么-
count
is less than 0.count
小于0。-or-
-要么-
startIndex
andcount
do not specify a valid section in theList<T>
.startIndex
和count
不指定List<T>
的有效节。
The most likely reason is the third one, but startIndex
is 0
(inside the range) and count
is far below l.Count
so the section within the list is 0 to 4, which is valid. 最可能的原因是第三个,但是
startIndex
是0
(在范围内)并且count
远远低于l.Count
所以列表中的部分是0到4,这是有效的。
What am I doing wrong and how to fix it? 我做错了什么以及如何解决?
According to the documentation you linked FindLastIndex(...)
is doing a backward search, meaning it goes to 0
, not to Count-1
根据您链接的文档
FindLastIndex(...)
正在进行向后搜索,这意味着它会转到0
,而不是Count-1
You are providing a 0 as the starting point and there are in fact less than 5 (your count) elements between 0 and 0. 您提供0作为起点,实际上在0和0之间有少于5(您的计数)元素。
Changing your to Code something like this will fix it: 将您的代码更改为此类代码将修复它:
List<int> l = new List<int>();
l.Add(1); l.Add(1); l.Add(1); l.Add(1); l.Add(1);
l.Add(1); l.Add(1); l.Add(1); l.Add(1); l.Add(1);
l.Add(1); l.Add(1); l.Add(1); l.Add(1); l.Add(1);
l.FindLastIndex(l.Count - 1, 5, v => v != 1);
you want (assuming you want to search the first 5 entries backwards) 你想要(假设你想向后搜索前5个条目)
l.FindLastIndex(4, 5, v => v != 1);
as the index is a start of a backwards search 因为索引是向后搜索的开始
so it will search from index 4 for 5 counts back to index 0 所以它将从索引4搜索5个计数回到索引0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.