Lists and RemoveAt()

Hi,

I have a List that I use RemoveAt() through a loop, what I’d like to know say if I have a List of 100 waypoints, waypointList, then I save a List of positions, waypointPos, then loop though the List of waypoints using RemoveAt() and say the List of waypointPos are 2, 18, 20, 100.

So then it will RemoveAt(waypointPos i ) … but is there no 100 now because positions 2, 18, 20 have been removed so now the waypointList has only 97 positions … Is that correct?
I ask this because if the waypointPos List does have hold the number of the total of the waypointList I get an error.
Thanks.
javascript*_</em></em></em></em></em></em> <em><em><em><em><em><em><em>* for (var l = 0; l < waypointPos.Count; l++) { waypointList.RemoveAt(waypointPos[l]); }*</em></em></em></em></em></em></em> <em><em><em><em><em><em>_*

Yes, the list will no longer have 100 elements.

Instead of using 100, try using “waypointList.Count - 1” to get the last element of the list.

3 Likes

This seem to work …

    var tempPos : int;
    for (var l = 0; l < waypointPos.Count; l++)
    {
        waypoints.RemoveAt(waypointPos[l-tempPos]);
        tempPos++;
    }
1 Like

What I do is using a temp list where I Add the elements I want to keep or remove.
Then use this temp list as it is or to remove elements from my other list.

You can still use Remove instead of RemoveAt but Remove cost more CPU since it have to browse all the list to find the object to remove.

It’s useful when you want to remove objects from differents indexes without any order restriction.

1 Like

Yeah, I need to re think this as my solution above now gives me the error at 0 because of the waypointPos[l-tempPos] :eyes:

Why not use Linq? for smarter query’s

1 Like
        List<Vector3> positions = new List<Vector3>();

        // Populate
        for (int i = 0; i < 100; ++i)
        {
            positions.Add(new Vector3(0, Random.Range(0, 100), 0));
        }

        List<Vector3> positionsToRemove = new List<Vector3>();

        for (int i = 0; i < positions.Count; ++i)
        {
            if (positions[i].y <= 50)
            {
                positionsToRemove.Add(positions[i]);
            }
        }

        for (int i = 0; i < positionsToRemove.Count; ++i)
        {
            positions.Remove(positionsToRemove[i]);
        }

        int lessThan50Count = 0;

        for (int i = 0; i < positions.Count; ++i)
        {
            if (positions[i].y <= 50)
                lessThan50Count++;
        }

        print(lessThan50Count);

Indeed Linq may be way more powerful here

1 Like

Something along the lines of what @Fabian-Haquin mentioned, you could

  • Create a temp List
  • Iterate over the original
  • Push all the elements into the temp List ‘except’ the ones that need to be deleted
  • Clear the original and copy the temp to original list
1 Like

Thanks to everyone for their input … This is what I’ve gone for, iterate the list list backwards …
```javascript

  • for(var l = waypointPos.Count - 1; l > -1; l–)
    {
    waypoints.RemoveAt(waypointPos[l]);
    }*
    ```
    Seem to be working correctly every time …
2 Likes

Are you sure you are removing the right index each time ?

In a list of 10 objects, if you want to remove 2 then 5 then 6, using this method It will not work.

At first you remove the object at 2, so the object that was at 5 will be at 4.
Next you remove the object at 5 but it was the object at 6 !
Finally you remove the object at 6 but it was the object at 8

1 Like

Yeah, I’m really not concentrating on this am I, Found This and now I read it again that will work because it’s only looking for Null positions in the List not a precise position, your answer above makes total logic.

Looks like I’ll have to go your way, just trying to keep code to a minimum, thanks again for your input, much appreciated.

What I would do to keep the code to a minimum is to think how I would fill waypoints at first before removing some.
I don’t know your projects you can maybe fill waypoints list in a way where you just have to remove “the last 10 items” ?
Or always removing one item by one item by using delegates ? (with the right index each time of course).

For example, for a project I had to have a scoreboard, so when I inserted a new player to my list, I would use .Insert to just have it in right place directly instead of doing some sorting for the on-screen display.

Linq would definitely simplify the code.

HashSet<waypoint> waypoints;
List<waypoint> waypointsToRemove;

public void CleanupOnAisle3()
{
    waypointsToRemove.ForEach(w => waypoints.Remove(w));
    waypointsToRemove.Clear();
}

Frequent removals from a List don’t perform well, consider a HashSet instead if your waypoint list won’t contain duplicates (references to the same waypoint object) and you don’t need ordered access.

You may also want to consider a Dictionary if frequent removal performance is a consideration. The good thing about all of these is Unity has eliminated allocs from foreach loops as of 5.5, so using any of these is usually pretty convenient.

2 Likes

Just want to add that, when dealing with vector (3D float) as list type there is basically no performance difference when using Linq vs using for loops. How you implement Linq is important. MV10 example is a good one, thought i would do it a bit different.

2 Likes

I generate a set amount of waypoints then I go through the List of waypoint checking their distance between each other, and if too close their position is added to the waypointPos List then thats when I’m looking to remove them.

Then the process is repeated to only add the amount that has been removed from the list until I have the total of waypoints I’m looking for.

This is setoff to run in Start() then it will be used very few times in runtime.

It sounds like you’re repeating a lot of work that way (for example, if waypoints 1 and 2 have the desired distance, you don’t want to compare them to each other again). It seems it would be better to just check the generated waypoint against the existing list when it’s generated. Don’t add it if it doesn’t meet the criteria, just generate another one.

And once again, a single line of Linq makes it super easy:

public List<Waypoint> waypoints = new List<Waypoint>();

public void AddWaypoints(int listSize)
{
    while(waypoints.Count < listSize)
    {
        Waypoint w = GenerateNextWaypoint();
        if(waypoints.Any() && !w.DistanceTest(100f)) waypoints.Add(w);
    }
}

public class Waypoint
{
    public Vector3 pos;

    public bool DistanceTest(float maxDistance)
    {
        return waypoints.Any(w => Vector3.Distance(w.pos, pos) > maxDistance);
    }
}
2 Likes

I’m not used to use Linq, I really should force myself so it will become an habit :smile:.
Thanks for your examples MV10

1 Like

Yes, thank you for pointing me in this direction its great to learn new ways of doing things, as I’m still learning C and mostly written all my code in Javascript (a decision I took some while back and now are being to regret it) I’ll try and convert that into .js

Thanks all …

1 Like

It’s great for doing a lot with very little code, but you have to be cognizant of allocation. My game is turn-based for PC and fairly slow-moving, so I can afford to be a little sloppy for the sake of convenience – plus I’m the sole programmer and this is a hobby, so I make the rules :smile: … But here’s a good example of real code from my project where Linq packs a lot of functionality into a single line of code. However, FindAll does allocate a new list.

allShips.FindAll(s => s.config.DefensiveBatteries > 0).ForEach(s => s.FirePDLs(this));

That line was doing a lot more work when it was originally written. It could now be written without allocation by testing in the ForEach, I just haven’t bothered yet:

allShips.ForEach(s => if(s.config.DefensiveBatteries) > 0) s.FirePDLs(this));

And of course, with closures you could write an entire multi-line anonymous function like this:

allShips.Foreach(s => {
    if(s.config.DefensiveBatteries)
    {
        Debug.LogFormat("Ship {0} is firining PDLs.", s.name);
        s.FirePDLs(this);
    }
    else
    {
        Debug.LogFormat("Ship {0} has no PDLs.", s.name);
    }
});

Some people really hate this style but I find it pretty readable, personally.

That’s why I hate C# (but keep using it everyday), memory allocation is never obvious.

It just can be some kind of hell to debug something when you have a lot of stuff going on a single line where you can’t really dig behind.