无法将ListBox.ObjectCollection转换为(类型化的)数组 [英] Can't convert ListBox.ObjectCollection to a (typed) array

查看:49
本文介绍了无法将ListBox.ObjectCollection转换为(类型化的)数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将项目转换为String数组或用于填充ListBox.DataSource的类型.该类型已覆盖ToString(),但我似乎无法将其转换,甚至不能转换为String [].

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;

推荐答案

string[] a = ListBox1.Items.Cast<string>().ToArray();

当然,如果您打算对 a 进行的所有操作都在其上进行迭代,则不必调用ToArray().您可以直接使用从 Cast< string>()返回的 IEnumerable< string> ,例如:

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

这篇关于无法将ListBox.ObjectCollection转换为(类型化的)数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆