Cast ListView Items to List?

后端 未结 4 829
[愿得一人]
[愿得一人] 2021-02-13 11:02

How can I cast ListView.Items to a List?

This is what I tried:

List list = lvFiles.Items.Cast

        
4条回答
  •  傲寒
    傲寒 (楼主)
    2021-02-13 11:35

    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 list = lvFiles.Items.Cast()
                                     .Select(item => item.Text)
                                     .ToList();
    

提交回复
热议问题