Can#39;t convert ListBox.ObjectCollection to a (typed) array(无法将 ListBox.ObjectCollection 转换为(类型化)数组)
问题描述
我想将项目转换为字符串数组或用于填充 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().您可以直接使用 CastIEnumerable,例如:
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 转换为(类型化)数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:无法将 ListBox.ObjectCollection 转换为(类型化)数组
基础教程推荐
- WPF 模态进度窗口 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
