List -> Array

  • Thread starter Thread starter muscha
  • Start date Start date
M

muscha

Hello,

What's the easiest way to convert List -> Array in c#? Say for example the
same thing like in Java:

List list = new ArrayList();

Item[] items = (Item[]) list.toArray(new Item[list.size()]);

Is there a way to do this?

Thanks heaps,

/m
 
muscha said:
Hello,

What's the easiest way to convert List -> Array in c#? Say for example the
same thing like in Java:

List list = new ArrayList();

Item[] items = (Item[]) list.toArray(new Item[list.size()]);

Pretty similar over all. If your list is an ArrayList, you can call
ArrayList.ToArray directly, if not, use the ArrayList(ICollection)
constructor:
//assumes you have an IList list defined.
//the new array list is used to provide ToArray, not pretty but ToArray
isn't provided in
//IList or ICollection
ArrayList arr = new ArrayList(list);
Item[] items = (Item[])arr.ToArray(typeof(Item));
 
muscha said:
What's the easiest way to convert List -> Array in c#? Say for example the
same thing like in Java:

List list = new ArrayList();

Item[] items = (Item[]) list.toArray(new Item[list.size()]);

Is there a way to do this?

Yes - and it's actually rather nicer in .NET/C#:

ArrayList list = new ArrayList();
....

Item[] items = (Item[]) list.ToArray (typeof(Item));

Note that it needs to be declared as ArrayList rather than IList, as
IList doesn't have the ToArray method, unfortunately.
 
List list = new ArrayList();
Item[] items = (Item[]) list.toArray(new Item[list.size()]);

Is there a way to do this?

Yes - and it's actually rather nicer in .NET/C#:

ArrayList list = new ArrayList();
...

Item[] items = (Item[]) list.ToArray (typeof(Item));

Note that it needs to be declared as ArrayList rather than IList, as
IList doesn't have the ToArray method, unfortunately.

Ah that's why. I wonder why ToArray() is not defined in IList?

/m
 
Back
Top