简体   繁体   中英

Iterating through arraylist and removing an object

Title says it all, I'm having some trouble iterating through an arraylist I've made (songs) and removing a specific song once it's been found. I've confirmed that the locations are correct and have tried manually entering in a song's location to no avail.

    Sub delete(location As String)
    Dim tempS As Song
    For Each tempS In songs
        If tempS.getLocation().toLower().Equals(location) Then
            songs.Remove(tempS)
        End If
        Exit For
    Next
End Sub

This project is still very much in its beginning stage and the only thing a song has associated with itself is it's stored location (ei C:\\Music\\Albums\\Once\\Nemo.mp3). Many thanks!

There are a couple of issues in your code.

Firstly you are not comparing the same case because location does not have a .ToLower() after it.

Secondly you are potentially removing an item from your list whilst still iterating through it. This can cause issues.

You can improve this considerably by using linq. That way you can do it all in one line:

Public Sub DeleteByLocation(location As String)
    songs.RemoveAll(Function(x) x.GetLocation().Equals(location, StringComparison.OrdinalIgnoreCase))
End Sub

Change RemoveAll to Remove to improve performance if you are certain that there will only be one matching location

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM