如何从列表中删除多个条目而不超出范围?

时间:2010-10-05 20:32:26

标签: c#

我有一个包含许多值(例如200)的整数列表。

List<int> ExampleList;

另一个关于整数的列表,它包含需要从ExampleList中删除的索引。但是,此列表未排序。

List<int> RemoveFromExampleList;

如果它已经排序,我会运行一个反向循环并删除所有值,如下所示:

for (int i = (RemoveFromExampleList.Count-1); i >=0; i--)
{
    ExampleList.RemoveAt(RemoveFromExampleList[i]);
}

我是否必须对RemoveFromExampleList进行排序,还是有另一种方法从ExampleList中删除不必要的值?

如果我必须排序,最简单的排序方法是什么?是否有任何内置的C#库/方法进行排序?

6 个答案:

答案 0 :(得分:8)

如果RemoveFromExampleList是索引列表,则必须对其进行排序并按降序工作以根据这些索引进行删除。以任何其他方式执行此操作将导致您删除不想删除的值。

答案 1 :(得分:2)

您可以使用标记值替换要删除的值,即您知道列表中没有出现的值,然后删除该值的所有匹配项。

答案 2 :(得分:2)

这是一个班轮。

ExampleList.RemoveAll(x => RemoveFromExampleList.Contains(ExampleList.IndexOf(x)));

答案 3 :(得分:1)

您的选择是排序,是的。按降序对删除列表进行排序,然后按索引删除。

// perform an orderby projection, remove
foreach (int index in RemoveFromExampleList.OrderByDescending(i => i)
    ExampleList.RemoveAt(index);

// actually sort the list, then remove
RemoveFromExampleList.Sort((a,b) => b.CompareTo(a));
foreach (int index in RemoveFromExampleList)
    ExampleList.RemoveAt(index);

(假设没有重复项,请在列表/投影上使用.Distinct()否则。)

答案 4 :(得分:0)

如果你真的厌倦了对列表进行排序,你可以使列表成为可以为空的整数列表:

List<int?> ints;

然后,您可以使“删除列表”中的值无效,并使用RemoveAll方法删除空值。

但这显然有点像黑客。

答案 5 :(得分:0)

你可以像这样使用LINQ / Lambda:

//示例从另一个列表中删除项目             列表masterList = new List();             masterList.Add(1);             masterList.Add(1);             masterList.Add(2);             masterList.Add(3);

        List<int> itemsToRemove = new List<int>();
        itemsToRemove.Add(1);
        itemsToRemove.Add(2);
        itemsToRemove.Add(3);

        List<int> cleanList = new List<int>();
        foreach (int value in itemsToRemove)
        {
            masterList = masterList.Where(x => x != value).ToList();
        }