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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 10:51:42  来源:igfitidea点击:

Cast ListView Items to List<string>?

c#winformslistviewitem

提问by user2214609

How can I cast ListView.Itemsto 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 ListViewItemCollectionis exactly what it sounds like - a collection of ListViewItemelements. 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 Textproperty of a ListViewItem, you can do that easily:

如果你想要一个字符串列表,每个字符串都取自Texta的属性ListViewItem,你可以很容易地做到这一点:

List<string> list = lvFiles.Items.Cast<ListViewItem>()
                                 .Select(item => item.Text)
                                 .ToList();

回答by p.s.w.g

The Castmethod 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 Selectmethod:

使用以下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);