如何遍历和更新列表 [英] How to iterate and update a list
问题描述
我有这个问题很多随着时间的推移,如果我重复一个列表,和修改的过程中列表导致异常。
I have had this problem lots over time, if I iterate a list, and modify the list in the process it causes an exception.
List<string> list = new List<string>()
{
"one",
"two",
"three"
};
foreach (string item in list)
{
if (item == "two")
{
list.Remove(item);
}
}
我已经提出了自己的解决方案,而是希望听到你的解决方案。
I have come up with my own solutions, but interested to hear your solutions.
推荐答案
那么你可以在这种情况下,使用LINQ:
Well you could use linq in this case:
list = list.Where(s => s != "two").ToList();
在很长的路要走它是构建项目的第二列表中删除,然后再通过该列表中删除从第一个列表中的项目迭代。下面是一些例子code:
The long way to go about it would be to build a second list of items to remove, and then iterate through that list removing items from the first list. Here is some example code:
请注意,我强烈建议你用简单的LINQ的解决方案,而不是做这种方式,但如果由于某种原因,LINQ的是不是一种选择,你可以这样:
Please note, I highly recommend going with the simple Linq solution, and not doing it this way, but if for some reason Linq is not an option for you this should work:
List<string> toRemove = new List<string>();
foreach (string item in list)
{
if (item == "two")
{
toRemove.Add(item);
}
}
foreach(string item in toRemove)
{
list.Remove(item);
}
这篇关于如何遍历和更新列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!