How can I delete an item from an array in VB.NET?

前端 未结 11 1724
别那么骄傲
别那么骄傲 2020-12-05 18:14

How can I delete an item from an array in VB.NET?

11条回答
  •  一个人的身影
    2020-12-05 18:21

    That depends on what you mean by delete. An array has a fixed size, so deleting doesn't really make sense.

    If you want to remove element i, one option would be to move all elements j > i one position to the left (a[j - 1] = a[j] for all j, or using Array.Copy) and then resize the array using ReDim Preserve.

    So, unless you are forced to use an array by some external constraint, consider using a data structure more suitable for adding and removing items. List, for example, also uses an array internally but takes care of all the resizing issues itself: For removing items, it uses the algorithm mentioned above (without the ReDim), which is why List.RemoveAt is an O(n) operation.

    There's a whole lot of different collection classes in the System.Collections.Generic namespace, optimized for different use cases. If removing items frequently is a requirement, there are lots of better options than an array (or even List).

提交回复
热议问题