[英]Removing item from a Generic List
I'm trying to remove an item from a Generic List
which is bound to a repeater control. 我正在尝试从绑定到转发器控件的
Generic List
删除一个项目。
So far I've got a remove method (after scouring the interwebs) that should of been working: 到目前为止,我已经有了一个应该可以正常工作的删除方法(在检查完interweb之后):
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. 我了解您无法创建要删除的
List<>
的new
实例。 So, that's why I used the Linq
statement to find the previous details. 因此,这就是为什么我使用
Linq
语句查找以前的详细信息的原因。
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() . 您也可以尝试List(T).RemoveAll() 。 Refer to LINQ: How to Use RemoveAll without using For loop with Array .
请参考LINQ:如何在不使用For循环和Array的情况下使用RemoveAll 。 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循环而不是foreach,然后进行修改。
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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.