Deleting items in a list at once by index in c#
I am looking for a way to remove a set of indexes from a list AT ONCE. By this i mean, I have a list of indices for ex, 0,1,5,7 that i want to remove from a string list of animals. I need a way 开发者_C百科to remove all the animals at the indices 0,1,5,7 in one shot. THis is because if i iterate through the animals list and delete the animal at 0,1,5,7 at each iteration, the list structure changes and the indeces no longer apply to the updated animal list.
Thanks
Well, one option is to delete them starting with the highest one instead. For example:
foreach (var index in indexesToDelete.OrderByDescending(x => x))
{
list.RemoveAt(index);
}
For example, removing item 5 doesn't affect items 0-4.
In addition to what @Jon Skeet said, another option is to copy the list, leaving out the items you don't want.
List<string> copy = new List<string>(list.Count - indexesToDelete.Count);
for (int index = 0; index < list.Count; index++)
{
if (!indexesToDelete.Contains(index))
copy.Add(list[index]);
}
list = copy;
I am not claiming this is an improvement over Jon's answer, only that it is an alternative. I can imagine some scenerios where this approach may be preferred.
精彩评论