C# 如何从排序列表中删除元素?
嗨,我有一个列表,其中有一些旧值。我想删除它们,但它显示了未处理的异常,即集合在创建对象后发生了更改。系统。无效的操作异常C# 如何从排序列表中删除元素?,c#,winforms,linq,C#,Winforms,Linq,嗨,我有一个列表,其中有一些旧值。我想删除它们,但它显示了未处理的异常,即集合在创建对象后发生了更改。系统。无效的操作异常 foreach (var item in list)// here is exception { if (DateTime.Parse(item.Key.ToShortDateString()) >DateTime.Parse("12.09.2020")) {
foreach (var item in list)// here is exception
{
if (DateTime.Parse(item.Key.ToShortDateString()) >DateTime.Parse("12.09.2020"))
{
panel.Controls.Add(new Label()
{
Text = item.Key.ToString().Remove(10) + "\n" + item.Key.ToString().Remove(0, 10) + "\n" + item.Value.ToString(),
AutoSize = true
});
month.AddBoldedDate(item.Key);
}
else list.Remove(item.Key); // I want to delete an old element
}
我怎样才能解决这个问题。对不起我的英语。如果我不使用我的手机,它就正常工作了 在迭代列表时,不应删除元素,而应在迭代之前删除元素,如下所示:
list.RemoveAll(item => DateTime.Parse(item.Key.ToShortDateString()) > DateTime.Parse("12.09.2020"));
// at this point all of those items are removed you can continue with our loop without the else statement
foreach (var item in list)// here is exception
{
panel.Controls.Add(new Label()
{
Text = item.Key.ToString().Remove(10) + "\n" + item.Key.ToString().Remove(0, 10) + "\n" + item.Value.ToString(),
AutoSize = true
});
month.AddBoldedDate(item.Key);
}
不要在迭代列表时删除元素,而应该在迭代之前删除它们,如下所示:
list.RemoveAll(item => DateTime.Parse(item.Key.ToShortDateString()) > DateTime.Parse("12.09.2020"));
// at this point all of those items are removed you can continue with our loop without the else statement
foreach (var item in list)// here is exception
{
panel.Controls.Add(new Label()
{
Text = item.Key.ToString().Remove(10) + "\n" + item.Key.ToString().Remove(0, 10) + "\n" + item.Value.ToString(),
AutoSize = true
});
month.AddBoldedDate(item.Key);
}
枚举列表时不能更改它。您应该迭代列表中要删除的项
foreach(var item in list)
{
//...
else
{
keysToRemove.Add(item.Key);
}
}
foreach(var key in keysToRemove)
{
list.Remove(key);
}
枚举列表时不能更改它。您应该迭代列表中要删除的项
foreach(var item in list)
{
//...
else
{
keysToRemove.Add(item.Key);
}
}
foreach(var key in keysToRemove)
{
list.Remove(key);
}
将
foreach(列表中的var项)
更改为foreach(list.ToList()中的var项)
当列表中有类似3,4,5,6,7的项时,删除项5,然后以3,4,6,7结束,并使用foreach循环跳过6。所以改为使用(inti=list.Count-1;i>=0;i--){var item=list[i]}。从列表的末尾开始,然后移到开头将解决问题。foreach(列表中的var项)到foreach(列表中的var项。ToList())它正在工作。将foreach(列表中的var项)
更改为foreach(列表中的var项。ToList())
如果列表中有3,4,5,6,7这样的项目,并且删除了项目5,那么最终将得到3,4,6,7,并使用foreach循环跳过6。所以改为使用(inti=list.Count-1;i>=0;i--){var item=list[i]}。从列表末尾开始,然后移到开头将解决issue.foreach(列表中的var项)到foreach(列表中的var项。ToList())的问题。排序列表不包含全部删除的定义。排序列表不包含全部删除的定义。