1

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!

Matt Wilko
  • 26,994
  • 10
  • 93
  • 143
Novastorm
  • 1,439
  • 3
  • 26
  • 40
  • 3
    is the location in .equals(location) also to lower? If it isn't, than it won't match. – Kat Aug 26 '14 at 15:40
  • 2
    I think you want that `Exit For` inside the `If` block. Be careful when iterating through any array and deleting items during iteration as you can't always be sure what you are iterating after you delete one of them. – Matt Wilko Aug 26 '14 at 15:40
  • it'll be C:\Music\Albums\Once\Nemo.mp3 versus c:\music\albums\once\nemo.mp3 – Kat Aug 26 '14 at 15:40
  • 2
    Also, matt's right. Move that exit. – Kat Aug 26 '14 at 15:41
  • Thank you both! Moving the Exit For did the trick, can't believe it was something that simple! Haha yes my bad I forgot to mention that all songs are converted to lower before being added to the arraylist. – Novastorm Aug 26 '14 at 15:46

1 Answers1

0

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

Matt Wilko
  • 26,994
  • 10
  • 93
  • 143