简体   繁体   中英

.NET 3.5: How to remove from list using the 3.5 functions

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.

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM