Rene
Rene

Reputation: 1

Add a List<object> or Arraylist to an array of CustomObject[]

I have tried many ways like Cast<CustomObject>, as Customobject and ToArray(Customobject) but nothing worked.

How can I add List or ArrayList via AddRange to a CustomObject[] Array?

Code is really difficult. But if you have some time you can get the complete source of the destination list from here: http://www.codeproject.com/Articles/4012/C-List-View-v1-3?msg=3844172#xx3844172xx

This is a Custom Listview I activated a combobox for the second column, so I can select diferrent values for a cell. But before this, I have to add something to select. This is the hole problem.

Update: Firstly, thanks for the help ! Secondly, Found a solution in the comments from the website with the source. Had to add some code and changed the destination custom array to a List

Upvotes: 0

Views: 840

Answers (5)

Matthias Meid
Matthias Meid

Reputation: 12523

Strictly speaking you cannot add elements to an array, since an array's length remains constant over its lifetime. There are two things you can do:

Create a new array

myArray = myTList.ToArray() // generic)
myArray = myArrayList.Cast<CustomObject>().ToArray() // cast, non-generic
myArray = myArrayList.OfType<CustomObject>().ToArray() // filter by type, non-generic

Set elements of an array

myArray[x] = myTList[y] // generic
myArray[x] = (CustomObject)myArrayList[y] // non-generic

I recommend you to take the generic collection whenever possible. They provide you additional type safety. Casting object variables cause runtime errors you could detect at compile time by using generic types.

If you actually want to add elements to an existing collection, you may try to use a dynamic collection type rather than an array: List<T> : IList<T> or LinkedList<T> : ICollection<T> are a good point to start, or maybe more specific types like Stack<T> or Queue<T>.

Upvotes: 0

Spontifixus
Spontifixus

Reputation: 6660

If you are unsure whether all of your objects are of the type CustomObject try

var result = list.OfType<CustomObject>.ToArray();

Upvotes: 0

verdesmarald
verdesmarald

Reputation: 11866

list.Cast<CustomObject>().ToArray()

Will work as long as the things in the list are actually CustomObject. If they might be other types, you can use OfType<CustomObject>() instead of Cast. This will filter out anything of an incompatible type.

Upvotes: 6

Nikhil Agrawal
Nikhil Agrawal

Reputation: 48568

If its a List<CustomObject> then let us say

CustomObject[] coarr = list_of_customobject.ToArray();

If its an ArrayList then

CustomObject[] coarr = arraylist.OfType<CustomObject>().ToArray();   

Upvotes: 0

Rotem
Rotem

Reputation: 21927

Assuming the objects really are instances of CustomObject, use LINQ Select method:

objList.Select(o => o as CustomObject).ToArray();

Otherwise you will get an array of null.

Upvotes: 1

Related Questions