Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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."

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
392 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.

foreach(int indice in lstIndices.OrderByDescending(v => v))
{
     lstOriginal.RemoveAt(indice);
}

Here is why: let's say have a list of five items, and you'd like to remove items at indexes 2 and 4. If you remove the item at 2 first, the item that was at index 4 would be at index 3, and index 4 would 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...