VB.NET Filtering ListItems Problem

后端 未结 5 680
北荒
北荒 2021-01-25 11:15

I am trying to filter a ListBox based on the presence of a string. Basically, if there is a ListItem that doesn\'t contain the string then I want to remove all ListItems that do

5条回答
  •  礼貌的吻别
    2021-01-25 11:29

    When removing items from a list there are a couple of options. As you've discovered, modifying the collection in a foreach loop isn't going to work. A for loop that counts down is the answer as @balpha mentioned.

    Another option is to store a list of items in a separate list, then iterate over that to remove items from the original list. Yet another option is to use LINQ.

    Sample list:

    Dim stringList As New List(Of String)
    stringList.Add("W:foo")
    stringList.Add("bar")
    stringList.Add("barW:")
    stringList.Add("foo")
    

    Reverse For Loop

    For i As Integer = stringList.Count - 1 To 0 Step -1
        If stringList(i).IndexOf("W:") > -1 Then stringList.RemoveAt(i)
    Next
    

    ForEach with 2 Lists

    Dim removeList As New List(Of String)
    ' store items to remove here
    For Each s As String In stringList
        If s.IndexOf("W:") > -1 Then removeList.Add(s)
    Next
    ' remove stored items here
    For Each s As String In removeList
        stringList.Remove(s)
    Next
    

    LINQ

    In this snippet I filter on IndexOf = -1 instead of > -1 to keep what I want rather than filter what I don't want.

    stringList = stringList.Where(Function(s) s.IndexOf("W:") = -1).ToList()
    

提交回复
热议问题