如何从数组中删除元素 [英] How to remove elements from an array
问题描述
嗨我工作的一些遗留code的推移沿
Hi I'm working on some legacy code that goes something along the lines of
for(int i = results.Count-1; i >= 0; i--)
{
if(someCondition)
{
results.Remove(results[i]);
}
}
要我好像不好的做法被删除的元素,同时还通过迭代循环,因为你会被修改索引。
To me it seems like bad practice to be removing the elements while still iterating through the loop because you'll be modifying the indexes.
这是一个正确的假设?
是否有这样做的更好的办法?我想使用LINQ,但我在2.0框架
Is there a better way of doing this? I would like to use LINQ but I'm in 2.0 Framework
推荐答案
去除实际上是OK,因为你会向下到零,只是你已经通过了将被修改的索引。这code居然会打破的另一个原因是:它以 results.Count
,而应 results.Count -1 $启动C $ C>因为数组的索引从0开始。
The removal is actually ok since you are going downwards to zero, only the indexes that you already passed will be modified. This code actually would break for another reason: It starts with results.Count
, but should start at results.Count -1
since array indexes start at 0.
for(int i = results.Count-1; i >= 0; i--)
{
if(someCondition)
{
results.RemoveAt(i);
}
}
编辑:
正如指出的 - 实际上你必须处理一些在你的伪code的List。在这种情况下,它们在概念上是相同的(因为列表内部使用数组),但如果你使用一个数组你有一个长度
属性(而不是计数
属性),你不能添加或删除项目。
As was pointed out - you actually must be dealing with a List of some sort in your pseudo-code. In this case they are conceptually the same (since Lists use an Array internally) but if you use an array you have a Length
property (instead of a Count
property) and you can not add or remove items.
使用列表上方的解决方案肯定是简洁的,但可能不容易理解别人,必须维持code(在列表中即特别是迭代向后) - 另一种解决方案是先确定项目除去,然后在第二遍中除去那些项目。
Using a list the solution above is certainly concise but might not be easy to understand for someone that has to maintain the code (i.e. especially iterating through the list backwards) - an alternative solution could be to first identify the items to remove, then in a second pass removing those items.
刚刚替补的MyType
与您正在处理的实际类型:
Just substitute MyType
with the actual type you are dealing with:
List<MyType> removeItems = new List<MyType>();
foreach(MyType item in results)
{
if(someCondition)
{
removeItems.Add(item);
}
}
foreach (MyType item in removeItems)
results.Remove(item);
这篇关于如何从数组中删除元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!