C# 将 ListView 项目投射到 List<string>?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17932873/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Cast ListView Items to List<string>?
提问by user2214609
How can I cast ListView.Items
to a List<string>
?
我怎样才能投射ListView.Items
到 a List<string>
?
This is what I tried:
这是我尝试过的:
List<string> list = lvFiles.Items.Cast<string>().ToList();
but I received this error:
但我收到了这个错误:
Unable to cast object of type 'System.Windows.Forms.ListViewItem' to type 'System.String'.
无法将“System.Windows.Forms.ListViewItem”类型的对象转换为“System.String”类型。
采纳答案by Jon Skeet
A ListViewItemCollection
is exactly what it sounds like - a collection of ListViewItem
elements. It's nota collection of strings. Your code fails at execution time for the same reason that this code would fail at compile time:
AListViewItemCollection
正是它听起来的样子 -ListViewItem
元素的集合。它不是字符串的集合。您的代码在执行时失败的原因与此代码在编译时失败的原因相同:
ListViewItem item = lvFiles.Items[0];
string text = (string) item; // Invalid cast!
If you want a list of strings, each of which is taken from the Text
property of a ListViewItem
, you can do that easily:
如果你想要一个字符串列表,每个字符串都取自Text
a的属性ListViewItem
,你可以很容易地做到这一点:
List<string> list = lvFiles.Items.Cast<ListViewItem>()
.Select(item => item.Text)
.ToList();
回答by p.s.w.g
The Cast
method will essentially try to perform a box/unbox, so it will fail if the items in the list aren't already strings. Try this instead:
该Cast
方法本质上将尝试执行装箱/拆箱,因此如果列表中的项目还不是字符串,它将失败。试试这个:
List<string> list = lvFiles.Items.Cast<ListViewItem>()
.Select(x => x.ToString()).ToList();
Or this
或这个
List<string> list = lvFiles.Items.Cast<ListViewItem>()
.Select(x => x.Text).ToList();
回答by Sriram Sakthivel
Try something like this
尝试这样的事情
List<string> list = lvFiles.Items.Cast<ListViewItem>().Select(x=> x.ToString()).ToList();
回答by Felipe Oriani
Try this using the Select
method:
使用以下Select
方法试试这个:
for list text:
对于列表文本:
List<string> listText = lvFiles.Items.Select(item => item.Text).ToList();
for list values:
对于列表值:
List<string> listValues = lvFiles.Items.Select(item => item.Value).ToList();
Or maybe, for both:
或者,对于两者:
Dictionary<string, string> files = lvFiles.Items.ToDictionary(key => key.Value, item => item.Text);