How to remove elements from a generic list while iterating over it?
Iterate your list in reverse with a for loop:
for (int i = safePendingList.Count - 1; i >= 0; i--)
{
// some code
// safePendingList.RemoveAt(i);
}
Example:
var list = new List<int>(Enumerable.Range(1, 10));
for (int i = list.Count - 1; i >= 0; i--)
{
if (list[i] > 5)
list.RemoveAt(i);
}
list.ForEach(i => Console.WriteLine(i));
Alternately, you can use the RemoveAll method with a predicate to test against:
safePendingList.RemoveAll(item => item.Value == someValue);
Here's a simplified example to demonstrate:
var list = new List<int>(Enumerable.Range(1, 10));
Console.WriteLine("Before:");
list.ForEach(i => Console.WriteLine(i));
list.RemoveAll(i => i > 5);
Console.WriteLine("After:");
list.ForEach(i => Console.WriteLine(i));
Python: How to remove elements from list while iterating through it without skipping future iterations
You are right. You need an additional list. But there is an easier solution.
def print_numTXTs(fileList):
counter = 0
for file in list(fileList):
if file.name[-4:] == ".txt":
counter +=1
if file.name == "a.txt":
fileList.remove(file)
The secret is "list(fileList)". You creating an additional list and iterates over this.
Just as powerful are list compressions. In your example it should work like this. I have not tried now...only quickly written here.
fileList = [ file for file in fileList if file.name != "a.txt" ]
Remove an item in a list while it's in a foreach loop c#
Try just creating another temporary list for the items that need to be deleted then when your done looping you can just delete the ones in the temp list.
List<Type> temp = new List<Type>()
foreach(item in mainList)
{
if (item.Delete)
{
temp.Add(item);
}
}
foreach (var item in temp)
{
mainList.Remove(item);
}
Best way to iterate over a list and remove items from it?
Willy-nilly you have to loop over the list, and the for
loop is the most efficient one:
for (int i = safePendingList.Count - 1; i >= 0; --i)
if (condition)
safePendingList.RemoveAt(i);
If you want to remove in range (not in the entire list), just modify for loop:
// No Enumarable.Range(1, 10) - put them into "for"
for (int i = Math.Min(11, safePendingList.Count - 1); i >= 1; --i)
if (condition)
safePendingList.RemoveAt(i);
Or if you have to remove items in forward looping:
for (int i = 0; i < safePendingList.Count;) // notice ++i abscence
if (condition)
safePendingList.RemoveAt(i);
else
i += 1; // ++i should be here
On the contrary safePendingList.ToList()
creates a copy of initial safePendingList
and this means memory and CPU overhead:
// safePendingList.ToList() - CPU and Memory overhead (copying)
foreach (var item in safePendingList.ToList()) {
if (condition)
myList.Remove(item); // Overhead: searching
}
However, the most reasonable plan in many cases is just to let .Net work for you:
safePendingList.RemoveAll(item => condition);
How to remove items from a list while iterating?
You can use a list comprehension to create a new list containing only the elements you don't want to remove:
somelist = [x for x in somelist if not determine(x)]
Or, by assigning to the slice somelist[:]
, you can mutate the existing list to contain only the items you want:
somelist[:] = [x for x in somelist if not determine(x)]
This approach could be useful if there are other references to somelist
that need to reflect the changes.
Instead of a comprehension, you could also use itertools
. In Python 2:
from itertools import ifilterfalse
somelist[:] = ifilterfalse(determine, somelist)
Or in Python 3:
from itertools import filterfalse
somelist[:] = filterfalse(determine, somelist)
Remove an item from a generic list while in a foreach
The simplest approach is to remember all the elements you want to remove, then remove them later:
var tilesToRemove = new List<CollisionTiles>();
foreach (var tile in map.CollisionTiles)
{
if (!tile.IsTransparent)
{
player.Collision(tile.Rectangle, map.Width, map.Height);
}
else if (player.PickUp(tile, map.Width, map.Height))
{
tilesToRemove.Add(tile);
}
camera.Update(player.Position, map.Width, map.Height);
}
// Remove all the ones we didn't want
foreach (var tile in tilesToRemove)
{
map.Remove(tile);
}
// Potentially call camera.Update here? We don't know if it uses the tiles
(It's not clear why you're calling camera.Update
that often, by the way - could you not call it once after the loop?)
Java: How to remove elements from a list while iterating over/adding to it
Split off a method stop() from stopAndRemove(). Then write the loop with an explicit iterator, do the stop and then iterator.remove().
"and" in a method name is a code smell.
C# List - Removing items while looping / iterating
If you need to remove elements then you must iterate backwards so you can remove elements from the end of the list:
var data=new List<string>(){"One","Two","Three"};
for(int i=data.Count - 1; i > -1; i--)
{
if(data[i]=="One")
{
data.RemoveAt(i);
}
}
However, there are more efficient ways to do this with LINQ (as indicated by the other answers).
Related Topics
What Is the Yield Keyword Used For in C#
Download File of Any Type in ASP.NET MVC Using Fileresult
Best Way to Implement Keyboard Shortcuts in a Windows Forms Application
How to Ignore a Property in Class If Null, Using Json.Net
What's a "Static Method" in C#
How to Evaluate C# Code Dynamically
Convert a Unicode String to an Escaped Ascii String
The Located Assembly'S Manifest Definition Does Not Match the Assembly Reference
What Are Your Favorite Extension Methods For C# (Codeplex.Com/Extensionoverflow)
How to Add a Timeout to Console.Readline()
Convert Utc/Gmt Time to Local Time
How to Call Stored Procedure in Entity Framework 6 (Code-First)