2012-01-27 36 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() 

這在邏輯上是正確的。請以此爲基準,並讓我們知道結果。

相關問題