是否将ListView项目转换为List< string> ;? [英] Cast ListView Items to List<string>?
问题描述
如何将ListView.Items
强制转换为List<string>
?
这是我尝试过的:
List<string> list = lvFiles.Items.Cast<string>().ToList();
但我收到此错误:
无法将类型为"System.Windows.Forms.ListViewItem"的对象转换为类型为"System.String".
Unable to cast object of type 'System.Windows.Forms.ListViewItem' to type 'System.String'.
推荐答案
ListViewItemCollection
的确切含义是-一个ListViewItem
元素的集合.它不是字符串的集合.您的代码在执行时失败,原因与该代码在编译时失败的原因相同:
A ListViewItemCollection
is exactly what it sounds like - a collection of ListViewItem
elements. It's not a collection of strings. Your code fails at execution time for the same reason that this code would fail at compile time:
ListViewItem item = lvFiles.Items[0];
string text = (string) item; // Invalid cast!
如果想要一个字符串列表,每个字符串都取自ListViewItem
的Text
属性,则可以轻松地做到这一点:
If you want a list of strings, each of which is taken from the Text
property of a ListViewItem
, you can do that easily:
List<string> list = lvFiles.Items.Cast<ListViewItem>()
.Select(item => item.Text)
.ToList();
这篇关于是否将ListView项目转换为List< string> ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!