.NET 3.5:如何使用3.5函数从列表中删除

时间:2010-02-21 09:28:33

标签: c# .net-3.5

我有一个包含对象的List。每个对象都有一个ID。我想删除其ID出现在给定集合中的所有对象。 我知道在3.5中有一些函数,比如RemoveAll,可以方便搜索和删除。

该函数的原型是:

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

从列表中删除的最佳方法是什么?
感谢。

2 个答案:

答案 0 :(得分:4)

list.RemoveAll(item => idsToRemoveAreTheKeys.ContainsKey(item.ID));

这会检查列表中的每个项目一次,并在字典中执行密钥查找,因此它大致为O(N),因为密钥查找速度很快。

如果您循环使用按键,则每次都必须通过列表进行线性搜索,这需要O(N * M),其中M是字典中的键数。

答案 1 :(得分:0)

对于List,您可以这样做:

    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)