kopelence
kopelence

Reputation: 193

C# LastIndexOf not giving correct result

in this particular line of code :

correct = Array.LastIndexOf(turns.ToArray(), false, 4, 0);

I get result correct = -1, well how is this even possible ?

turns[0] up to turns[3] are equal to false turns[4]=true and turns[5]=false is it possible to be caused because the last index i want to be looked up to is 4 and it has value different than the required one ?

Upvotes: 1

Views: 165

Answers (3)

user5771133
user5771133

Reputation:

Try this out:

correct = Array.LastIndexOf(turns.ToArray(), false, turns.Length, turns.Length);

What were you doing wrong:

  • never hard code array length (especially in your case, when the array is filled with values)
  • the first index is actually the starting search index from backwards, and the second index is actually the count, i.e. how many items to search (MSDN constructor clarification)

Update 1:

Made a mistake on the starting index and the count number. Updated the changes, thank you @Steve for pointing it out.

Upvotes: 0

kMalik
kMalik

Reputation: 16

Your count indicates searching 0 elements in the section.

correct = Array.LastIndexOf(turns.ToArray(), false, 4, 2);

Upvotes: 0

ChaseMedallion
ChaseMedallion

Reputation: 21764

The issue is with the last argument (count). This restricts the number of elements searched. You are restricting it to search 0 elements starting at index 4. Thus, it doesn't find anything.

Upvotes: 4

Related Questions