Elegant way to convert Collection to Array[]

  • Thread starter Thread starter Tamir Khason
  • Start date Start date
T

Tamir Khason

How can I convert (elegant way) Collection to Array without looping and new
instances.
E.G:
I want to add elements of one menu to other, so
secondMenu.MenuItems.AddRange(firstMenu.MenuItems); //Error here: Argument
'1': cannot convert from 'System.Windows.Forms.Menu.MenuItemCollection' to
'System.Windows.Forms.MenuItem[]'

So please advice.
 
The ICollection interface provides a "CopyTo" method that copies the
collection data into an array. However, you can be pretty sure it does this
with a loop.

There is no generic to "convert" a collection to an array that does not
involve copying the elements of the collection: The collection could contain
anything, from a linked list to a database recordset; The only way to
convert these to an array is to copy them element by element, as the memory
layout of an array is completely different from say, a linked list.

Niki
 
The ArrayList class can be instantiated with an ICollection instance (which
is quite elegant).
You could then convert the ArrayList to a regular Array using the ToArray
function.
The Array object doesn't have any mechanism to instantiate or fill itself
from an ICollection instance.
 
To be clear: ToArray can be used like this:

MyClass[] myClassArray = (MyClass[])myArrayList.ToArray(typeof(MyClass));

Christian

John Wood said:
The ArrayList class can be instantiated with an ICollection instance (which
is quite elegant).
You could then convert the ArrayList to a regular Array using the ToArray
function.
The Array object doesn't have any mechanism to instantiate or fill itself
from an ICollection instance.

--
John Wood
EMail: first name, dot, second name at priorganize.com


Tamir Khason said:
How can I convert (elegant way) Collection to Array without looping and new
instances.
E.G:
I want to add elements of one menu to other, so
secondMenu.MenuItems.AddRange(firstMenu.MenuItems); //Error here: Argument
'1': cannot convert from 'System.Windows.Forms.Menu.MenuItemCollection' to
'System.Windows.Forms.MenuItem[]'

So please advice.
 
Back
Top