是否将ListView项目转换为List< string&gt ;? [英] Cast ListView Items to List<string>?

查看:402
本文介绍了是否将ListView项目转换为List< string&gt ;?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将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!

如果想要一个字符串列表,每个字符串都取自ListViewItemText属性,则可以轻松地做到这一点:

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&lt; string&gt ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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