Klausos Klausos
Klausos Klausos

Reputation: 16060

Delete elements from a List using iterator

There is a List<Integer> tabulist that contains values [2,0,5]. Also, there is a List this.getRoutes() which contains keys [0,1,2,3,4,5]. I need to delete elements [2,0,5] from this.getRoutes(). So, as a result I must get the following entries in this.getRoutes():

[1,3,4]

Here is my code:

iter = this.getRoutes().iterator();

while(iter.hasNext())
{
    Route r = iter.next();
    if (tabulist.contains(r.getRouteKey()))
    {
        iter.remove();
    }
}

The problem is that r.getRouteKey() is always 0. Therefore, I am always deleting the first elements from this.getRoutes(). I don't understand why the iterator does not move to [1,2,3,4,5].

How to solve this issue? Maybe I should also delete values from tabulist?

Upvotes: 1

Views: 59

Answers (1)

Sigur
Sigur

Reputation: 317

I didn't test my code, but here are 3 variations on the theme. You should test them in case I made a mistake, but they give an idea of the general idea.

using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;

public class Class1
{

public static List<int> RemoveItems1(List<int> OriginalValues, List<int> ValuesToRemove)
{
    List<int> result = new List<int>();

    foreach (object item_loopVariable in OriginalValues) {
        item = item_loopVariable;
        if ((!ValuesToRemove.Contains(item))) {
            result.Add(item);
        }
    }

    return result;
}

public static List<int> RemoveItems2(List<int> OriginalValues, List<int> ValuesToRemove)
{
    List<int> result = OriginalValues;

    foreach (object item_loopVariable in ValuesToRemove) {
        item = item_loopVariable;
        if ((OriginalValues.Contains(item))) {
            result.Remove(item);
        }
    }

    return result;
}

public static List<int> RemoveItems3(List<int> OriginalValues, List<int> ValuesToRemove)
{
    List<int> result = OriginalValues;

    foreach (object item_loopVariable in from item1 in ValuesToRemovewhere (OriginalValues.Contains(item1))) {
        item = item_loopVariable;
        result.Remove(item);
    }

    return result;
}
}

The first one adds only elements to get to a result. Like I said in my comment. The second one removes elements from a result that is set to the parameter Originalvalues. The last one is basically the same as number two, but uses LINQ. I'm using static methods because then this can be used in any situation and you don't need to instantiate a class to do this. Which adds extra unnecessary code.

Upvotes: 1

Related Questions