Removing item from list in foreach loop


New member
Mar 7, 2016
Programming Experience
Hello, I am new to C# and I have a quick question.

I made a class that is named LinkInfo.

In the class LinkInfo there are 6 variables

int x1 (coord 1)
int x2 (coord 2)
int y1 (coord 3)
int y2 (coord 4)
Actor (name of an actor)
UseCase (name of a usecase)

This class is made to draw lines between two different x/y coords and get you info about what actor you linked with what usecase.

Now, I want to try and remove an item from a list containing LinkInfo data. private List<LinkInfo> LineList = new List<LinkInfo>();

I want to delete the item that has an Actor-variable containing my own string.


string X = "Hello"

foreach (LinkInfo ll in LineList)
LineList.Remove(ll.Actor = X)

I hope you understand what I mean since I am not that familair with all the terms around C#
Firstly, you don't remove items from a list while enumerating it. It doesn't work. If you want to remove items from a list like that then you either use a 'for' loop and work backwards, so removing an item doesn't affect the indexes of those you're yet to examine, or you create another list and enumerate that.

Secondly, you're trying to remove an item IF it satisfies a particular condition. How do you usually test whether something satisfies a condition? I've given you a hint.

So, while it's not the only option, I would recommend to you that you use a 'for' loop that works backwards, test whether the current item satisfies the condition and then remove it if it does. Hey, there's another hint!
Top Bottom