Can't convert ListBox.ObjectCollection to a (typed) array

房东的猫 提交于 2019-12-18 23:38:22

问题


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;

回答1:


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



回答2:


The Cast method doesn't seem to be available anymore. I came up with an other solution :

String[] array = new String[ListBox.Items.Count]
ListBox.Items.CopyTo(array, 0);

The CopyTo method takes an existing array and insert the items at the given index and forward.

I don't know if this is very efficient, but its consistent and easy to write.



来源:https://stackoverflow.com/questions/2599125/cant-convert-listbox-objectcollection-to-a-typed-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!