我有许多类都实现了相同的接口。 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
使用.NET 2.0在VB.NET中有更好的方法吗?
答案 0 :(得分:1)
我能看到的选项很少。如果指定列表的容量,则性能将提高。因为List.Add()需要一些额外的步骤来调整集合的大小。
为什么不使用stringbuilder,并在每个id的末尾添加逗号。
Dim builder As New 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()
这在逻辑上是正确的。请对此进行基准测试并确认结果。