Lets say my ArrayList got 20 elements. Well, sometime in runtime I will want it to only have 10 elements, so the other 10 indexes(from 9 to 19) don't exis开发者_运维百科t at all. How do I do that?
Why are you using non-generic collections at all? Use List<T>
instead. And you can use the Remove()
method on it.
Since your working with ArrayLists, and not Arrays, just use ArrayList.Remove() for a single part, and ArrayList.RemoveRange(x, list.Count-x) for a range.
If you're looking to avoid using memory space for the elements that are not present, you can try with the TrimToSize method:
http://msdn.microsoft.com/en-us/library/system.collections.arraylist.trimtosize.aspx
It will minimize the array overhead, by limiting the capacity to the current items.
If they already exist, you'll need to remove them and then, call this method.
I'm not sure what you're looking for exactly, so more details would be great.
If you just want to remove the elements without changing the capacity, you can use ArrayList.RemoveRange:
http://msdn.microsoft.com/en-us/library/system.collections.arraylist.removerange.aspx
arrayList.RemoveRange(10, list.Count-10)
This method can be used with any other valid range, if you e.g. want to delete the first ten elements instead.
精彩评论