1

I'm dealing with a probably common situation that I don't even know how to formulate in a search.

I decided to ask for guidance, not necessarily to get any piece of code but to ask about what is the best approach for this kind of situation.

I have a list named arrIntIndexesOfJobsThatWillBeKilled containing the original indexes of the items that must be removed from another 5 lists.

However, when I remove an item from the other 5 lists, they are reindexed, and the indexes I once had in arrIntIndexesOfJobsThatWillBeKilled are now invalid.

I want to remove only the items linked to the original indexes...

What is the best algorithm to handle this situation?

arrIntIndexesOfJobsThatWillBeKilled = arrIntIndexesOfJobsThatWillBeKilled.Distinct.ToList

If arrIntIndexesOfJobsThatWillBeKilled.Count > 0 Then

    For Each Job As Integer In arrIntIndexesOfJobsThatWillBeKilled

        arrStrJobDescription2.RemoveAt(Job)
        arrStrPNDirectories2.RemoveAt(Job)
        arrIntJobIDDirectories2.RemoveAt(Job)
        arrStrSubDirectories2.RemoveAt(Job)
        arrStrNCFile2.RemoveAt(Job)

    Next

End If
Daniel Santos
  • 188
  • 2
  • 15
  • 1
    Does this answer your question? [How to remove elements from a generic list while iterating over it?](https://stackoverflow.com/questions/1582285/how-to-remove-elements-from-a-generic-list-while-iterating-over-it) – Charlieface May 22 '23 at 10:14

2 Answers2

3

You can change the order of removal to reverse one - delete bigger indexes first. Not fluent with VB, but in C# it will look like:

arrIntIndexesOfJobsThatWillBeKilled = arrIntIndexesOfJobsThatWillBeKilled
    .OrderByDescending(i => i) // assuming list of integers here, or .OrderDescending() for later framework
    .Distinct()
    .ToList();

And then proceed with deletion.

P.S.

If arrIntIndexesOfJobsThatWillBeKilled.Count > 0 Then check is redundant - foreach handles empty collections just fine.

Guru Stron
  • 102,774
  • 10
  • 95
  • 132
0

After the guidance of the collaborators here, this is the code that works:

If arrIntIndexesOfJobsThatWillBeKilled.Count > 0 Then

arrIntIndexesOfJobsThatWillBeKilled = arrIntIndexesOfJobsThatWillBeKilled.OrderByDescending(Function(i) i).Distinct.ToList

   For Each Job As Integer In arrIntIndexesOfJobsThatWillBeKilled

       arrStrJobDescription2.RemoveAt(Job)
       arrStrPNDirectories2.RemoveAt(Job)
       arrIntJobIDDirectories2.RemoveAt(Job)
       arrStrSubDirectories2.RemoveAt(Job)
       arrStrNCFile2.RemoveAt(Job)

   Next

End If

Many thanks for once again educating this mediocre coder...

Daniel Santos
  • 188
  • 2
  • 15