Go through the list and remove the miscellaneous items in .NET.

In C ++, using std::list

deleting an element is just a matter of erasing pointed to by the iterator. (The erase operator returns the next valid member of the list.)

In .NET, what's the best way to iterate over a list and remove items that match certain criteria?

+2


source to share


5 answers


Assuming you have List<T>

one, one efficient way is to iterate over the list in reverse order, removing items as you go:

for(int i = myList.Count-1; i--; i>=0)
{
    if (ShouldBeRemoved(myList[i]))
    {
        myList.RemoveAt(i);
    }
}

      



If you have it instead IEnumerable<T>

, it gets more complicated as you cannot change the list while iterating.

+4


source


List<T>

has a method RemoveAll

that takes a predicate and removes items: http://msdn.microsoft.com/en-us/library/wdka673a.aspx

dinosaurs.RemoveAll(AddressOf EndsWithSaurus)



Private Shared Function EndsWithSaurus(ByVal s As String) _
    As Boolean
    If (s.Length > 5) AndAlso _
        (s.Substring(s.Length - 6).ToLower() = "saurus") Then
        Return True
    Else
        Return False
    End If
End Function

      

+9


source


In .NET, you cannot modify the underlying collection while iterating with an enumerator. Therefore, you have options:

  • iterate over your list with a nice ol <<20> loop,

  • create a new list with no items matching your criteria:

    var list1 = ...; var list2 = list1.Where (item =>! criteria (item)). ToList ();

(I used C # for this example, but you should be able to convert it to VB).

+2


source


if you are talking about foreach and using IEnumerator the answer is that you cannot remove anything from IEnumerable by iterating through it. The only way is to store something (element indices) in another list and then delete them in a loop

But here's the cookie: http://www.koders.com/csharp/fidF2C8E1786AE76101911914CCA9286E25B398AED6.aspx?s=textbox

"Lets you change the underlying collection in the middle of the foreach"

+1


source


What about:

    Dim lst As New List(Of String)

    While lst.Count > 0
        lst.RemoveAt(0)
    End While

      

another solution

0


source







All Articles