【问题标题】:.NET 3.5: How to remove from list using the 3.5 functions.NET 3.5:如何使用 3.5 函数从列表中删除
【发布时间】:2010-02-21 09:28:33
【问题描述】:

我有一个包含对象的列表。每个对象都有一个 ID。我想删除其 ID 出现在给定集合中的所有对象。 我知道在3.5中有RemoveAll等功能可以方便查找和删除。

函数的原型是:

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

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

【问题讨论】:

    标签: c# .net-3.5


    【解决方案1】:
    list.RemoveAll(item => idsToRemoveAreTheKeys.ContainsKey(item.ID));
    

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

    如果您遍历键,则每次都必须对列表进行线性搜索,这需要 O(N*M),其中 M 是字典中键的数量。

    【讨论】:

      【解决方案2】:

      对于列表,您可以这样做:

          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)
      

      【讨论】:

        猜你喜欢
        • 2014-09-09
        • 2012-03-11
        • 1970-01-01
        • 1970-01-01
        • 2018-10-03
        • 2015-03-20
        • 2011-05-14
        • 1970-01-01
        • 2011-03-07
        相关资源
        最近更新 更多