How do I use LINQ to get all the Items that have a particular SubItem?

余生长醉 提交于 2019-12-24 00:55:25

问题


My software is designed to encrypt and decrypt files. The user loads the files to be processed into a ListView control. In the control, each item is the file path with one subitem, the type of process (ENCRYPT or DECRYPT).

I need to get a list of all ITEMS (the file paths) that have the "ENCRYPT" subitem, preferably with LINQ. Currently, my code looks like this:

Dim enclist As New ArrayList()
For i As Int32 = 0 To (lvwLoad.Items.Count - 1)
    If lvwLoad.Items(i).SubItems(1).Text = "ENCRYPT" Then
        enclist.Add(lvwLoad.Items.Item(i).Text)
        count += 1
    End If
Next

I tried this:

Dim list As IEnumerable(Of String) = From item In lvwLoad.Items 
                                     Where item.SubItems(1).Text = "ENCRYPT"

But this statement can't access the SubItems() array. I know there's probably something simple I'm missing, but I can't figure it out.

EDIT: I know I can do this:

Dim enclist As New List(Of String)
For Each item As ListViewItem In lvwLoad.Items
    If item.SubItems(1).Text = "ENCRYPT" Then
        enclist.Add(item.Text)
    End If
Next

But I really want to know how to do this with LINQ.


回答1:


Try code below, you need to cast items to ListViewItem so that you can access SubItems

Dim list  = From item In lvwLoad.Items.Cast(Of ListViewItem) () _ 
                                     Where item.SubItems(1).Text = "ENCRYPT" 
                                     Select item.Text



回答2:


return lvwLoad.Items.Where(item => item.SubItems(1).Text = "ENCRYPT").Select(s => s.Text);

Dim list As IEnumerable(Of String) = From item In lvwLoad.Items 
                                 Where item.SubItems(1).Text = "ENCRYPT"
                                     Select item.Text

I hope this will help.



来源:https://stackoverflow.com/questions/14407902/how-do-i-use-linq-to-get-all-the-items-that-have-a-particular-subitem

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