Remove list elements at given indices

后端 未结 7 855
无人共我
无人共我 2020-12-20 13:19

I have a list which contains some items of type string.

List lstOriginal;

I have another list which contains idices which sh

相关标签:
7条回答
  • 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.

    0 讨论(0)
提交回复
热议问题