Reputation: 1
I don't know why this error happens. Please help me..
Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index
Here is my code:
var index = newData.FindIndex(x => x.description == item.description);
if (index ==-1)
index = 0;
var itemInIndex = newData[index];
The error I get is on this line, where it says:
var itemInIndex = newData[index];
Upvotes: 0
Views: 1487
Reputation: 32
Please check: Array.FindIndex
The zero-based index of the first occurrence of an element that matches the conditions defined by match, if found; otherwise, -1.
In the logic of your code is this sequence:
[Get index from newData where description == item.description]
[Check if is index == -1]
[Then asign index = 0]
[Get result from newData[0]]
This means that you're forcing index 0 (wich is not avalible in your array,list,etc...)
var index=newData.FindIndex(x => x.description== item.description);
if (index ==-1) throw new ArgumentNullException("description not found!");
var itemInIndex = newData[index];
Take a look how to manage Exceptions with: Try&Catch
Upvotes: 1
Reputation: 272
Firstly check your newData list is it empty. Because it's empty, and you're trying to get first element, but that element doesn't exists. Exception basically tells you that you're trying to index an element that is not exists.
Edit: Read link posted by @Charlieface to learn more about exception and indexes.
Upvotes: 0