Remove an item from Generic List inside foreach loop
When I am trying following code, getting error that list is modified, so how to remove product form the list on which I am looping
foreach (Product item in ProductList)
if(item.ID == 100)
ProductList.Remove(item)
2 Answers
Easiest way is to use .ToList() inside the foreach, so your code should be:
foreach (Product item in ProductList.ToList())
if(item.ID == 100)
ProductList.Remove(item)
|
2
|
Answered:
27 Feb 2013
Reputation: 242
|
|
I don't know whether you need foreach or not, if you want to remove all items where some criteria match, if this is the case then, use
ProductList.RemoveAll(x => x.ID == 100);
or use for loop in reverse order, like this
for(int II = ProductList.Length - 1; II >= 0; II--)
if(ProductList[II].ID == 100)
ProductList.Remove(ProductList[II])
|
0
|
Answered:
27 Feb 2013
Reputation: 1,418
|
|
This week users
