I have a list which contains some items of type string.
List<string> lstOriginal;
I have another list which contains idices which should be removed from first list.
List<int> lstIndices;
I’d tried to do the job with RemoveAt() method ,
foreach(int indice in lstIndices)
{
lstOriginal.RemoveAt(indice);
}
but it crashes and said me that “index is Out of Range.”
You need to sort the indexes that you would like to return from largest to smallest in order to avoid removing something at the wrong index.
Here is why: let’s say have a list of five items, and you’d like to remove items at indexes
2and4. If you remove the item at2first, the item that was at index4would be at index3, and index4would no longer be in the list at all (causing your exception). If you go backwards, all indexes would be there up to the moment when you’re ready to remove the corresponding item.