【问题标题】:Improve the way to replace the items of a List(Of String) inherited class?改进替换 List(Of String) 继承类的项目的方法?
【发布时间】:2015-10-24 11:15:36
【问题描述】:

我有一个以这种方式定义的类,它继承自 List(Of String),我有一些方法需要替换整个项目列表:

class something : Inherits List(Of String)

    <DebuggerStepThrough>
    Public Sub Trim(Optional ByVal trimChars As Char() = Nothing)

        Dim tmpList As New List(Of String)((From line As String In Me 
                                            Select line.Trim(trimChars)).ToList)

        Me.Clear()
        Me.AddRange(tmpList)

    End Sub

end class

或者这样避免使用 LINQ:

Public Sub Trim(Optional ByVal trimChars As Char() = Nothing)

    Dim tmpList As New List(Of String)
    For Each item As String In Me
        tmpList.Add(item.Trim(trimChars))
    Next item

    Me.Clear()
    Me.AddRange(tmpList)

End Sub

但我认为,如果我们谈论的是庞大的项目列表,那么清除项目并添加新项目并不是最有效的方式。

然后,我想改进我进行替换的部分,例如,而不是清除项目并添加新项目,我可以通过提高性能访问基础集合或其他方法以适当的方式执行这个逻辑?

编辑:

也许这种逻辑可能是最有效的?

Public Sub Trim(Optional ByVal trimChars As Char() = Nothing)

    For index As Integer = 0 To (Me.Count - 1)
        Me(index) = Me(index).Trim(trimChars)
    Next

End Sub

【问题讨论】:

    标签: vb.net linq list inheritance ienumerable


    【解决方案1】:

    对于大型列表,您的示例(见下文)在内存使用方面更有效,因为您避免需要第二个大型列表

    For index As Integer = 0 To (Me.Count - 1)
        Me(index) = Me(index).Trim(trimChars)
    Next
    

    对于小型列表,您采用哪种方法并不重要。创建第二个列表并在最后分配的好处是它将列表中所有字符串的修剪视为自主操作;也就是说,如果发生异常,列表中的字符串保持原来的状态。

    您可以考虑一种返回新列表的方法:

        class something : Inherits List(Of String)
    
            <DebuggerStepThrough>
            Public Function Trim(Optional ByVal trimChars As Char() = Nothing)
    
                Dim list As New something
                For index As Integer = 0 To (Me.Count - 1)
                   String s = Me(index);
                   If s IsNot Nothing Then
                       list.Add(s.Trim(trimChars))
                   End If
                Next
                Return list;
            End Function
    
        end class
    

    此外,您可能需要考虑在调用 Trim() 之前检查字符串是否为空(null),否则您将收到异常。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-17
      • 2010-10-22
      • 2015-09-04
      • 2015-12-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多