我有一个循环遍历列表中的元素.我需要根据某些条件从循环中删除此列表中的元素.当我尝试在C#中执行此操作时,我得到一个例外.显然,不允许从列表中删除正在迭代的元素.使用foreach循环观察到该问题.有没有任何标准的方法来解决这个问题?
注意:我能想到的一个解决方案是仅为迭代目的创建列表副本,并从循环内的原始列表中删除元素.我正在寻找一种更好的方法来解决这个问题.
Bra*_*ith 16
使用List<T>该ToArray()方法时,在这种情况下有很大帮助:
List<MyClass> items = new List<MyClass>();
foreach (MyClass item in items.ToArray())
{
if (/* condition */) items.Remove(item);
}
Run Code Online (Sandbox Code Playgroud)
替代方法是使用for循环而不是foreach,但是每当删除元素时你必须减少索引变量,即
List<MyClass> items = new List<MyClass>();
for (int i = 0; i < items.Count; i++)
{
if (/* condition */)
{
items.RemoveAt(i);
i--;
}
}
Run Code Online (Sandbox Code Playgroud)
Luk*_*keH 14
如果您的列表是实际的,List<T>那么您可以使用内置RemoveAll方法根据谓词删除项目:
int numberOfItemsRemoved = yourList.RemoveAll(x => ShouldThisItemBeDeleted(x));
Run Code Online (Sandbox Code Playgroud)
您可以使用 LINQ 通过过滤掉项目来用新列表替换初始列表:
IEnumerable<Foo> initialList = FetchList();
initialList = initialList.Where(x => SomeFilteringConditionOnElement(x));
// Now initialList will be filtered according to the condition
// The filtered elements will be subject to garbage collection
Run Code Online (Sandbox Code Playgroud)
这样你就不用担心循环了。
您可以使用整数索引来删除项目:
List<int> xs = new List<int> { 1, 2, 3, 4 };
for (int i = 0; i < xs.Count; ++i)
{
// Remove even numbers.
if (xs[i] % 2 == 0)
{
xs.RemoveAt(i);
--i;
}
}
Run Code Online (Sandbox Code Playgroud)
然而,这可能是奇怪的阅读和难以维护,特别是如果循环中的逻辑变得更复杂.