tags:

views:

103

answers:

2

I have a List with objects. Each object has an ID. I want to remove all the objects which their IDs appear in a given collection. I know that in 3.5 there are functions such as RemoveAll that can facilitate the search and remove.

the function's prototype is:

internal SomeObject removeFromMe(Dictionary<string, string> idsToRemoveAreTheKeys)

What's the best way to remove from the list?
Thanks.

+3  A: 
list.RemoveAll(item => idsToRemoveAreTheKeys.ContainsKey(item.ID));

This checks each item in the list once, and performs a key lookup in the dictionary, so it's roughly O(N) because key lookups are fast.

If you looped through the keys, you'd have to do a linear search through the list each time, which would require O(N*M), where M is the number of keys in the dictionary.

Daniel Earwicker
A: 

For List you can do this:

    Dim sam As New List(Of Integer) From {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
    sam.RemoveAll(Function(x) x Mod 2 = 0)

    var sam = New List<int> {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
    sam.RemoveAll( x => x % 2 = 0)
Jonathan Allen