Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing from list while iterating through a shallow copy of it

Tags:

c#

.net

list

I know that removing from a list while iterating through it it's not a good idea but what about getting a shallow copy of it and iterating through that while removing from the original list?

Example:

public class myClass
{
    public int id { get; set; }
    public string name { get; set; }
}

List<myClass> list = new List<myClass>();

// getting a shallow copy with FindAll
List<myClass> copy = list.FindAll(e => e.id > 10);

for (int i = 0; i < copy.Count; i++) 
{
    // do stuff with copy[i]
    list.RemoveAll(e => e.id == copy[i].id);
}

If copy is just a list of pointers to list's elements, to what will the pointers point from the copy after i remove from the original list?

like image 893
osmiumbin Avatar asked Dec 05 '22 23:12

osmiumbin


2 Answers

When you are removing items from original list, you are not removing items from memory, you are removing them from the list it self, they are still in memory and copy has references to them.

For example consider you are a student in a school and you are attending in math and physics class , if math teacher removes you from list of students in his class you are still in the list of physics class students and you are still a student in that school!

Both list and copy have some references to some items in memory, you are just adding and removing the references to them. If you remove all the references to an item in memory then garbage collector will remove the item from memory. just like if you do not attend in any class in a school then you are not a student in that school anymore!

like image 112
Hamid Pourjam Avatar answered Dec 24 '22 14:12

Hamid Pourjam


even simpler (shorter):

foreach (var element in list.ToList()) 
{
    // do stuff with copy[i]
    list.RemoveAll(e => e.id == element.id);
}

The LINQ ToList() creates a temporary copy on the fly.

As long as you acces your list elements with something different from the index (as in your example an ID) you need not to worry about changing indices.

like image 43
DrKoch Avatar answered Dec 24 '22 15:12

DrKoch