Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast ListView Items to List<string>?

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'.

like image 669
user2214609 Avatar asked Jul 29 '13 19:07

user2214609


1 Answers

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();
like image 128
Jon Skeet Avatar answered Oct 13 '22 13:10

Jon Skeet