views:

186

answers:

2

I want to convert the items to a String array or the type that I used to fill the ListBox.DataSource. The type has overridden ToString() but I can't seems to get it converted, not even to String[].

String[] a = (String[])ListBox1.Items;
Contacts[] b = (Contacts[])ListBox1.Items;
A: 
String[] a = ListBox1.Items.Select(item => item.ToString()).ToArray();
Contact[] b = ListBox1.Items.Select(item => (Contact)item).ToArray();

or something like that

darja
I'm not sure that will work. `Items` is an `IEnumerable`, but `Select` takes an `IEnumerable<T>`.
Marcelo Cantos
It in fact does not work.
Sdry
+2  A: 
string[] a = ListBox1.Items.Cast<string>().ToArray();

Of course, if all you plan to do with a is iterate over it, you don't have to call ToArray(). You can directly use the IEnumerable<string> returned from Cast<string>(), e.g.:

foreach (var s in ListBox1.Items.Cast<string>()) {
    do_something_with(s);
}

Or, if you have some way to convert strings to Contacts, you can do something like this:

IEnumerable<Contacts> c = ListBox1.Items.Cast<string>().Select(s => StringToContact(s));
Marcelo Cantos
I only had to convert it to pass it as a parameter to a method. It only accepted String[] or Contact[].Very helpful, thanks!
D. Veloper