After two years of C#, my VB.NET is a bit rusty. I have two Lists. Let’s call them originalList and targetList. Here is my C# code:
for(int i = 0; i<originalList.Count; i++) { bool isMatch = false; foreach (string t in targetList) { if(String.Compare(originalList[i], t, true) == 0) { isMatch = true; break; } } if(isMatch) { originalList.RemoveAt(i); i--; } }
And my VB.NET code is this:
Dim i as Integer For i = 0 To originalList.Count - 1 Dim isMatch as boolean = false For Each t As String In targetList If String.compare(originalList(i), t, true) = 0 Then isMatch = true Exit For End If Next If isMatch Then originalList.RemoveAt(i) i -= 1 End If Next
But I got an index-out-of-range error with my VB.NET code. Where did I get it wrong?
Consider this – it’s a far more elegant way of achieving what you’re trying to do – and that is removing items from your original list that appear in your target list. Consider the following lists:
And here’s how I’d remove all the items from the original that appear in the target…
Which in C# would be written:
The less code you use to achieve a task, the less chance that coding bugs could be introduced.
Side Note: This is very similar to an algorithm to test subsets. If you want to find out if set A is a subset of B, then you can iterate through B removing any corresponding items from A. Once you’ve finished iterating through B, if there are any items left in A, then it wasn’t a subset of B. If there are no items left, then it was a subset of B.