2012-01-27 96 views
0

我有许多类都实现相同的接口。例如将(T)的列表转换为以逗号分隔的字符串的ID

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()方法的字符串的方法。

这是我到目前为止有:

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 

有没有使用.NET 2.0中VB.NET这样做的更好的办法?

回答

1

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

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

昏暗Builder作为新的StringBuilder()

For Each obj As IModelWithIdentity In collection 
      builder.Append(obj.GetId()).append(",") 
Next 
Dim res = builder.ToString() 

但是,这可能会在结尾处添加一个额外的逗号。

您可以使用索引器和传统的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() 

这在逻辑上是正确的。请以此为基准,并让我们知道结果。

相关问题