Vb.net 将(T的)列表转换为Id为'的逗号分隔字符串;s

Vb.net 将(T的)列表转换为Id为'的逗号分隔字符串;s,vb.net,.net-2.0,Vb.net,.net 2.0,我有许多类都实现了相同的接口。e、 g Public Class IncidentAsset Implements IModelWithIdentity Private _assetId As Int16 Private _otherAsset As String Private _asset As Asset Public Property AssetId() As Int16 Get Return _ass

我有许多类都实现了相同的接口。e、 g

Public Class IncidentAsset
    Implements IModelWithIdentity

    Private _assetId As Int16
    Private _otherAsset As String

    Private _asset As Asset

    Public Property AssetId() As Int16
        Get
            Return _assetId
        End Get
        Set(ByVal value As Int16)
            _assetId = value
        End Set
    End Property

    Public Property OtherAsset() As String
        Get
            Return _otherAsset
        End Get
        Set(ByVal value As String)
            _otherAsset = value
        End Set
    End Property

    Public Property Asset() As Asset
        Get
            Return _asset
        End Get
        Set(ByVal value As Asset)
            _asset = value
        End Set
    End Property

    Public Function GetId() As String Implements IModelWithIdentity.GetId
        Return _assetId.ToString()
    End Function
End Class
我有另一个对象和这些对象的列表

    Public Property IncidentAssetsDamaged() As List(Of IncidentAsset)
        Get
            Return _incidentAssetsDamaged
        End Get
        Set(ByVal value As List(Of IncidentAsset))
            _incidentAssetsDamaged = value
        End Set
    End Property
我需要编写一个方法,使用接口的GetId()方法返回一个逗号分隔的Id字符串

这就是我到目前为止所做的:

    Public Shared Function ToCommaSeparatedStringOfIds(Of T)(ByVal collection As List(Of T)) As String

        Dim array As List(Of String) = New List(Of String)

        For Each obj As IModelWithIdentity In collection
            array.Add(obj.GetId())
        Next

        Return String.Join(",", array.ToArray)
    End Function

在VB.NET中使用.NET 2.0是否有更好的方法来实现这一点?

我看到的选项很少。如果指定列表的容量,则性能将提高。因为List.Add()需要额外的步骤来调整集合的大小

为什么不使用stringbuilder,并在每个id的末尾附加逗号呢

作为新StringBuilder()的尺寸生成器

但这可能会在末尾添加一个额外的逗号

您可以使用索引器和常规for循环对其进行排序

Dim builder As New StringBuilder()
     For i = 0 To collection.Count - 2
          builder.Append(collection(i).GetId()).append(",")
     Next
     builder.Append(collection(collection.Count -1))

    Dim res = builder.ToString()
这在逻辑上是正确的。请对此进行基准测试,并告知结果

Dim builder As New StringBuilder()
     For i = 0 To collection.Count - 2
          builder.Append(collection(i).GetId()).append(",")
     Next
     builder.Append(collection(collection.Count -1))

    Dim res = builder.ToString()