Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FindLastIndex ArgumentOutOfRangeException when parameter count is less than List.Count

Tags:

c#

list

I'm puzzled with a problem regarding C# List, the code below throws 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:

ArgumentOutOfRangeException

startIndex is outside the range of valid indexes for the List<T>.

-or-

count is less than 0.

-or-

startIndex and count do not specify a valid section in the 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.

What am I doing wrong and how to fix it?

like image 740
PaperBirdMaster Avatar asked Sep 20 '18 11:09

PaperBirdMaster


2 Answers

According to the documentation you linked FindLastIndex(...) is doing a backward search, meaning it goes to 0, not to 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.

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);
like image 128
Milster Avatar answered Sep 17 '22 12:09

Milster


you want (assuming you want to search the first 5 entries backwards)

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

like image 23
Keith Nicholas Avatar answered Sep 20 '22 12:09

Keith Nicholas