How do you trim an arraylist?

  • Thread starter Thread starter dotnw
  • Start date Start date
D

dotnw

I have my own strongly typed collection class, and I added in this new
sub:

Public Sub TrimResults(ByVal iElementsToKeep As Integer)

Dim myArray() As clsMyClass

MyBase.InnerList.CopyTo(0, myArray, 0, iElementsToKeep)
MyBase.InnerList.Clear()
MyBase.InnerList.SetRange(0, myArray)

End Sub

...With the hope of getting the underlying innerlist to shed unwanted
elements at the end of it's list.

When run, I get this error on the .CopyTo line:

Array cannot be null. Parameter name: dest

Am I right in thinking that before I use the myArray variable, I have
to create a loop, and inside the loop, instantiate each and every
element of this array with a "new clsMyClass" line to make sure that
every element is ready to receive an element result from the CopyTo
operation?

Perhaps there's a good way of doing what I want to achieve, but my lack
of VB.NET knowledge is preventing me from seeing it.

Thank you, regards, dnw.
 
Hi,

Can you try this one.
Public Sub TrimResults(ByVal iElementsToKeep As Integer)

Dim myArray(iElementsToKeep-1) As clsMyClass
MyBase.InnerList.CopyTo(0, myArray, 0, iElementsToKeep)
MyBase.InnerList.Clear()
MyBase.InnerList.SetRange(0, myArray)

End Sub
I hope this helps,

Cor
 
Thanks very much Cor.

The working code is now:

Dim myArray(iElementsToKeep - 1) As clsSingleResult

MyBase.InnerList.CopyTo(0, myArray, 0, iElementsToKeep)
MyBase.InnerList.RemoveRange(0, MyBase.InnerList.Count)
MyBase.InnerList.AddRange(myArray)

Regards, dnw.
 
Back
Top