List <string> for object []

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

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

I suppose I could do foreach , but I would rather use AddRange(Object[]) as it is faster (and produces less code).

EDIT

The following works great:

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

However, for another note, any reason that I would like to perform above rather than:

 var list = new list<string>(); comboBox.AddRange(list.ToArray<object>()); 
+4
source share
6 answers

You can do this easily using the ToArray generic method:

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

You don't even need Cast<object> , because ToArray accepts an IEnumerable<T> , which is covariant for a parameter of a general type.

+11
source

You can use something like an explicit type change:

 object[] array = yourList.Cast<Object>().ToArray(); 

or just implicitly:

 yourcomboBox.AddRange(yourList.ToArray()); 
+4
source
 List<string> items = ...; cb.Items.AddRange(items.ToArray()); 
+1
source

Maybe this works:

 object[] myArray = myList.OfType<object>().ToArray(); 
+1
source

Link arrays are covariant ( slowly covariant ) with arrays of their base classes (and with arrays of their interfaces and other arrays), so you can:

 AddRange(mystrings.ToArray()); 

mystrings.ToArray() is a string[] covariant with object[] (so AddRange will accept it)

From 12.5 Covariance of Arrays

For any two reference types A and B, if there is an implicit reference conversion (section 6.1.4) or an explicit reference conversion (section 6.2.3) between A and B, then the same reference conversion of type A [R] to array type B [R]

0
source

If it's about convenience:

 public static class ObjectCollectionExtension { public static void AddAll<T>(this ComboBox.ObjectCollection self, IEnumerable<T> es) { foreach (var e in es) self.Add(e); } } 

It’s possible that generics are wrong, I'm a little rusty.

0
source

Source: https://habr.com/ru/post/1500699/


All Articles