简体   繁体   English

通过 c# 中的索引一次删除列表中的项目

[英]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.我的意思是,我有一个 ex, 0,1,5,7 的索引列表,我想从动物字符串列表中删除。 I need a way to remove all the animals at the indices 0,1,5,7 in one shot.我需要一种方法一次性移除索引为 0、1、5、7 的所有动物。 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.这是因为如果我遍历动物列表并在每次迭代中删除 0、1、5、7 处的动物,则列表结构会发生变化,并且索引不再适用于更新的动物列表。

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.例如,删除项目 5 不会影响项目 0-4。

In addition to what @Jon Skeet said, another option is to copy the list, leaving out the items you don't want.除了@Jon Skeet 所说的,另一种选择是复制列表,省略您不想要的项目。

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.我可以想象一些可能首选这种方法的场景。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM