Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert List<T> to object[]

I am looking for a one liner that transforms List<T> into object[]. It's one liner, so I am not interested in solutions such as foreach, or for...

Any takers?

Hint: No, both List<T>.ToArray() and List<T>.ToArray<object>() don't work.

Edit: Why List<T>.ToArray<object>() doesn't work? Because it can't compile.

like image 240
Graviton Avatar asked Apr 23 '09 14:04

Graviton


People also ask

How do I convert a list of strings to a list of objects?

Pass the List<String> as a parameter to the constructor of a new ArrayList<Object> . List<Object> objectList = new ArrayList<Object>(stringList);

How to convert a class into Array in Java?

Object[] toArray() With this method, Java converts the ArrayList object values into an array of objects of the class, Object. All classes are descendants of the class Object (beginning with uppercase O). The object of the class Object, has the method toString(). System.


2 Answers

mylist.Cast<object>().ToArray() 

That will only iterate once, by the way, in case you were wondering about the performance. O(n). :)

Why? Well, because Cast<object> will use deferred execution and won't actually do anything until the list is iterated by ToArray().

like image 70
Randolpho Avatar answered Oct 20 '22 18:10

Randolpho


List<T>.Select(x => x as object).ToArray(); 

Should return an object[].

like image 29
Çağdaş Tekin Avatar answered Oct 20 '22 18:10

Çağdaş Tekin