Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how properly remove item from list [duplicate]

Tags:

c#

Possible Duplicates:
Exception during iteration on collection and remove items from that collection
How to remove elements from a generic list while iterating around it?
Better way to remove matched items from a list

// tmpClientList is List<Client> type

if (txtboxClientName.Text != "")
    foreach (Client cli in tmpClientList)
        if (cli.Name != txtboxClientName.Text)
            tmpClientList.Remove(cli);

Error: "Collection was modified; enumeration operation may not execute."

How can i remove items from the list, in some simple way, without saving indexes of these items in another list or array, and removing them in another place in the code. Tried also RemoveAt(index) but it's exactly the same situation, modifying when loop runs.

like image 426
Krzysztof Szynter Avatar asked Jun 09 '10 12:06

Krzysztof Szynter


People also ask

How do I remove a specific repeated item from a list in Python?

If the order of the elements is not critical, we can remove duplicates using the Set method and the Numpy unique() function. We can use Pandas functions, OrderedDict, reduce() function, Set + sort() method, and iterative approaches to keep the order of elements.

How do I remove duplicates from a list without changing the order?

If you want to preserve the order while you remove duplicate elements from List in Python, you can use the OrderedDict class from the collections module. More specifically, we can use OrderedDict. fromkeys(list) to obtain a dictionary having duplicate elements removed, while still maintaining order.


1 Answers

Move backwards through the list.. that way removing an item does not affect the next item.

for(var i=tmpClientList.Count-1;i>=0;i--)
{
   if (tmpClientList[i].Name != txtboxClientName.Text)
            tmpClientList.RemoveAt(i);

}
like image 129
Jamiec Avatar answered Oct 06 '22 13:10

Jamiec