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 theList<T>
.-or-
count
is less than 0.-or-
startIndex
andcount
do not specify a valid section in theList<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?
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);
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With