简体   繁体   中英

Removing item from a Generic List

I'm trying to remove an item from a Generic List which is bound to a repeater control.

So far I've got a remove method (after scouring the interwebs) that should of been working:

Label lblMemberName = (Label)e.Item.FindControl("lblMemberName");        

switch (e.CommandName)
{
    case "RemoveMember":
        foreach (challenge.Member member in Members.Where(member => member.Name == lblMemberName.Text))
        {
            //This line doesnt work
            Members.Remove(member);
        }
        break;
}

Unfortunately, the actual removal apart of this scenario is not working.

I understand that you can't create a new instance of a List<> to delete. So, that's why I used the Linq statement to find the previous details.

What am I doing wrong and how could possibly ix it?

As above, you cannot modify the contents of a collection whilst iterating over it.

You could also try List(T).RemoveAll() . Refer to LINQ: How to Use RemoveAll without using For loop with Array . This is a more succinct solution than another list.

It's illegal to modify the list you're foreach-ing through. You can, however, convert it to a for-loop instead of foreach, and modify it then.

for (int i=0; i < Members.Count; i++)
{
    if (Members[i].Name == lblMemberName.Text)
        Members.RemoveAt(i--); // decrement because we just shrunk the list)
}

Get the member:

var member = Members.FirstOrDefault(i=>i.Name.Equals(thename));

And then remove it from list:

if (member != null) 
{ 
    Members.Remove(member); 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM