C# 从嵌套Foreach中的可观察集合中删除项
我有这些嵌套的Foreach:C# 从嵌套Foreach中的可观察集合中删除项,c#,wpf,for-loop,foreach,C#,Wpf,For Loop,Foreach,我有这些嵌套的Foreach: foreach (var item1 in ocChoicesinItem) { foreach (var item2 in temp.ItemsInInvoiceChoices) { if (item1.ChoicesId == item2.ChoicesId) ocChoicesinItem.Remove(item1);
foreach (var item1 in ocChoicesinItem)
{
foreach (var item2 in temp.ItemsInInvoiceChoices)
{
if (item1.ChoicesId == item2.ChoicesId)
ocChoicesinItem.Remove(item1);
}
}
从ocChoicesinItem中删除项时出现问题,导致以下错误:
有没有办法做到这一点
提前感谢。如果要删除集合中的项目,需要添加“ToList”语句:
foreach (var item1 in ocChoicesinItem.ToList())
{
foreach (var item2 in temp.ItemsInInvoiceChoices)
{
if (item1.ChoicesId == item2.ChoicesId)
ocChoicesinItem.Remove(item1);
}
}
如果要删除集合中的项,则需要添加“ToList”语句:
foreach (var item1 in ocChoicesinItem.ToList())
{
foreach (var item2 in temp.ItemsInInvoiceChoices)
{
if (item1.ChoicesId == item2.ChoicesId)
ocChoicesinItem.Remove(item1);
}
}
您不能在迭代集合时修改集合,因为在调用
MoveNext
尝试:
公共静态类扩展方法
{
公共静态int-RemoveAll(
此可观测集合(coll,Func条件)
{
var itemsToRemove=coll.Where(condition).ToList();
foreach(itemsToRemove中的var itemToRemove)
{
coll.移除(项目移除);
}
返回itemsToRemove.Count;
}
}
ocChoicesinItem.RemoveAll(x=>temp.ItemsInInvoiceChoices.Any(y=>y.ChoicesId==x.ChoicesId);
您不能在迭代集合时修改集合,因为调用MoveNext
尝试:
公共静态类扩展方法
{
公共静态int-RemoveAll(
此可观测集合(coll,Func条件)
{
var itemsToRemove=coll.Where(condition).ToList();
foreach(itemsToRemove中的var itemToRemove)
{
coll.移除(项目移除);
}
返回itemsToRemove.Count;
}
}
ocChoicesinItem.RemoveAll(x=>temp.ItemsInInvoiceChoices.Any(y=>y.ChoicesId==x.ChoicesId);
试试下面的方法
List<string> ocChoicesinItem = new List<string>{"One", "Two", "Three"};
List<string> ItemsInInvoiceChoices = new List<string> { "Three" };
ocChoicesinItem.RemoveAll(x => ItemsInInvoiceChoices.Contains(x));
List ocChoicesinItem=新列表{“一”、“二”、“三”};
列表项sininvoicechoices=新列表{“三”};
ocChoicesinItem.RemoveAll(x=>ItemsInInvoiceChoices.Contains(x));
显然,我使用的是字符串,因为我不知道您的集合包含什么类型;您可能需要比较谓词中的ID。尝试类似的方法
List<string> ocChoicesinItem = new List<string>{"One", "Two", "Three"};
List<string> ItemsInInvoiceChoices = new List<string> { "Three" };
ocChoicesinItem.RemoveAll(x => ItemsInInvoiceChoices.Contains(x));
List ocChoicesinItem=新列表{“一”、“二”、“三”};
列表项sininvoicechoices=新列表{“三”};
ocChoicesinItem.RemoveAll(x=>ItemsInInvoiceChoices.Contains(x));
显然,我使用的是字符串,因为我不知道集合包含什么类型;您可能需要比较谓词中的ID。只有Remove或RemoveAt,没有RemoveAll??我只是为此添加了一个扩展方法。或者……您可以使用Seb的答案。在迭代期间将
Enumerable
转换为列表。谢谢帮助告诉我,伙计们:)无论哪一个最适合他,只要移除或移除,就没有移除所有??我为此添加了一个扩展方法。或者……你可以使用Seb的答案。在迭代过程中将可枚举
转换为列表。谢谢你们的帮助伙计们:)无论哪一个最适合他,只要移除或移除,没有RemoveAll???@AbdusaLamelsher如果有:@Jay,没有,在observeCollection
中有moRemoveAll
方法,只有RemoveAt或RemoveAt,没有RemoveAll???@AbdusaLamelsher如果有:@Jay,没有,在observeCollection
中有moRemoveAll
方法