【发布时间】:2010-02-21 09:28:33
【问题描述】:
我有一个包含对象的列表。每个对象都有一个 ID。我想删除其 ID 出现在给定集合中的所有对象。 我知道在3.5中有RemoveAll等功能可以方便查找和删除。
函数的原型是:
internal SomeObject removeFromMe(Dictionary<string, string> idsToRemoveAreTheKeys)
从列表中删除的最佳方法是什么?
谢谢。
【问题讨论】:
我有一个包含对象的列表。每个对象都有一个 ID。我想删除其 ID 出现在给定集合中的所有对象。 我知道在3.5中有RemoveAll等功能可以方便查找和删除。
函数的原型是:
internal SomeObject removeFromMe(Dictionary<string, string> idsToRemoveAreTheKeys)
从列表中删除的最佳方法是什么?
谢谢。
【问题讨论】:
list.RemoveAll(item => idsToRemoveAreTheKeys.ContainsKey(item.ID));
这会检查列表中的每个项目一次,并在字典中执行一次键查找,因此它大致为 O(N),因为键查找速度很快。
如果您遍历键,则每次都必须对列表进行线性搜索,这需要 O(N*M),其中 M 是字典中键的数量。
【讨论】:
对于列表,您可以这样做:
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)
【讨论】: