Cast ListView Items to List?

后端 未结 4 824
[愿得一人]
[愿得一人] 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:12

    Try something like this

    List<string> list = lvFiles.Items.Cast<ListViewItem>().Select(x=> x.ToString()).ToList();
    
    0 讨论(0)
  • 2021-02-13 11:23

    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();
    
    0 讨论(0)
  • 2021-02-13 11:23

    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);
    
    0 讨论(0)
  • 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<string> list = lvFiles.Items.Cast<ListViewItem>()
                                     .Select(item => item.Text)
                                     .ToList();
    
    0 讨论(0)
提交回复
热议问题