最近,我写了很多看起来像这样的代码:
List<MyObject> myList = new List<MyObject>();
...
for(int i = 0; i < myList.Count; ++i)
{
if(/*myList[i] meets removal criteria*/)
{
myList.RemoveAt(i);
--i; //Check this index again for the next item
//Do other stuff as well
}
}
我只是变得有点偏执,也许 List 在删除时不保留对象顺序。我不太了解 C# 规范,无法确定。有人可以验证我是不是在找这种模式的麻烦吗?
编辑:也许我应该澄清一下,上面是一个非常简化的例子,如果需要删除该项目会发生更多事情,所以我不认为 List<T>.RemoveAll()
在这里非常适用。虽然这是一个很好的功能。我在 if()
中添加了评论上面的 block 特别提到了这一点。
最佳答案
List<T>
添加、插入和删除时将始终保持相对顺序;如果没有,它就不是列表。
这是 RemoveAt()
的(ILSpy'ed)代码:
public void RemoveAt(int index)
{
if (index >= this._size)
{
ThrowHelper.ThrowArgumentOutOfRangeException();
}
this._size--;
if (index < this._size)
{
Array.Copy(this._items, index + 1, this._items, index, this._size - index);
}
this._items[this._size] = default(T);
this._version++;
}
注意来自 index + 1
的数组副本至 index
;那就是被批发转移并将阵列“挤压”在一起的项目。但是绝对不会对元素进行重新排序。
关于c# - 从 C# List<T> 中删除项目是否会保留其他项目的订单?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6961606/