wpf 从嵌套 Foreach 中的 Observable 集合中删除项目
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23639766/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Remove item from Observable Collection in Nested Foreach
提问by Abdulsalam Elsharif
I have these nested Foreach :
我有这些嵌套的 Foreach :
foreach (var item1 in ocChoicesinItem)
{
foreach (var item2 in temp.ItemsInInvoiceChoices)
{
if (item1.ChoicesId == item2.ChoicesId)
ocChoicesinItem.Remove(item1);
}
}
The problem occur when remove item from ocChoicesinItem, gives me this error:
从 ocChoicesinItem 中删除项目时出现问题,给我这个错误:


Is there any way to accomplish this?
有什么办法可以做到这一点吗?
Thanks in advance.
提前致谢。
回答by Seb
You need to add 'ToList' statements if you want to remove items in the collection :
如果要删除集合中的项目,则需要添加“ToList”语句:
foreach (var item1 in ocChoicesinItem.ToList())
{
foreach (var item2 in temp.ItemsInInvoiceChoices)
{
if (item1.ChoicesId == item2.ChoicesId)
ocChoicesinItem.Remove(item1);
}
}
回答by Yuval Itzchakov
You can't modify a collection while iterating that collection, as you are making your Enumeratorinvalid when calling MoveNext
您不能在迭代该集合时修改该集合,因为您Enumerator在调用时使您的无效MoveNext
Try:
尝试:
public static class ExtensionMethods
{
public static int RemoveAll<T>(
this ObservableCollection<T> coll, Func<T, bool> condition)
{
var itemsToRemove = coll.Where(condition).ToList();
foreach (var itemToRemove in itemsToRemove)
{
coll.Remove(itemToRemove);
}
return itemsToRemove.Count;
}
}
ocChoicesinItem.RemoveAll(x => temp.ItemsInInvoiceChoices.Any(y => y.ChoicesId == x.ChoicesId);
回答by Jay
Try something like
尝试类似
List<string> ocChoicesinItem = new List<string>{"One", "Two", "Three"};
List<string> ItemsInInvoiceChoices = new List<string> { "Three" };
ocChoicesinItem.RemoveAll(x => ItemsInInvoiceChoices.Contains(x));
Obviously I am using strings as I don't know what type your collections contain; you may have to compare the ID's in the predicate.
显然我使用的是字符串,因为我不知道您的集合包含什么类型;您可能需要比较谓词中的 ID。

