在给定的索引中删除列表中的元素 [英] Remove list elements at given indices

查看:105
本文介绍了在给定的索引中删除列表中的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含字符串类型的一些物品的清单。

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

List<string> lstOriginal;



我有一个包含这应该从一个列表中删除idices另一个列表。

I have another list which contains idices which should be removed from first list.

List<int> lstIndices;



我已经试着用 RemoveAt移除()方式来完成这项工作,

I'd tried to do the job with RemoveAt() method ,

foreach(int indice in lstIndices)
{
     lstOriginal.RemoveAt(indice);
}



但它崩溃,说我的索引超出范围。

推荐答案

您需要在您想从最大的回报指标排序到最小,以。避免拆除错误的索引的东西。

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);
}



这是为什么:让我们说有五个项目的清单,你' D类似于在索引中删除项目 2 4 。如果您在 2 首先,这是在索引项 4 将处于指数<$ C $删除项目C> 3 和指数 4 将不再是列表中的所有(导致您的除外)。如果你倒着走,所有的指标是有多达当你准备删除相应的项目的时候。

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.

这篇关于在给定的索引中删除列表中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆