Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List<string> to object[]

Tags:

c#

I have a method that returns a List<string> and I'm trying to pass that to the AddRange(Object[]) method of a ComboBox.

How can I convert my List<string> to Object[]?

I suppose I could do a foreach but I'd rather use the AddRange(Object[]) as it's faster (and produces less code).

EDIT

The following works fine:

var list = new List<string>();
object[] array = list.ToArray<object>();
comboBox.AddRange(array);

However, on another note, any reason why I would want to perform the above instead of:

var list = new list<string>();
comboBox.AddRange(list.ToArray<object>());
like image 487
cogumel0 Avatar asked Sep 05 '13 10:09

cogumel0


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);


1 Answers

You can do it using ToArray generic method:

var list = new List<string>();
object[] array = list.ToArray<object>();

You don't even need Cast<object>, because ToArray takes IEnumerable<T> which is covariant on generic type parameter.

like image 166
MarcinJuraszek Avatar answered Nov 04 '22 05:11

MarcinJuraszek