无法将ListBox.ObjectCollection转换为(类型化)数组
我想将项目转换为String数组或我用来填充ListBox.DataSource的类型。 该类型已重写ToString()但我似乎无法将其转换,甚至不能转换为String []。
String[] a = (String[])ListBox1.Items; Contacts[] b = (Contacts[])ListBox1.Items;
string[] a = ListBox1.Items.Cast().ToArray();
当然,如果您计划使用a
进行迭代,则不必调用ToArray()。 您可以直接使用从Cast
返回的IEnumerable
,例如:
foreach (var s in ListBox1.Items.Cast()) { do_something_with(s); }
或者,如果您有某种方法将字符串转换为联系人,您可以执行以下操作:
IEnumerable c = ListBox1.Items.Cast().Select(s => StringToContact(s));
Cast
方法似乎不再可用。 我想出了另一个解决方案:
String[] array = new String[ListBox.Items.Count] ListBox.Items.CopyTo(array, 0);
CopyTo
方法接受现有数组并在给定索引处插入项目并转发。
我不知道这是否非常有效,但它一致且易于编写。