Cast ListView Items to List<string>?

只谈情不闲聊 提交于 2019-12-21 03:46:19

问题


How can I cast ListView.Items to 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'.


回答1:


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!

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();



回答2:


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:

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();



回答3:


Try something like this

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



回答4:


Try this using the Select method:

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);


来源:https://stackoverflow.com/questions/17932873/cast-listview-items-to-liststring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!