Go through the list and remove the miscellaneous items in .NET.
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.
source to share
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
source to share
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).
source to share
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"
source to share