Reputation: 8016
I'm currently writing a helper function in VB.NET to convert an array of enum values to a CSV, but I'm encounting a few difficulties....
I'm not sure what type of arguement my function should take if I want to make it generic enough to handle any enum I pass into it.
This is what I've got so far:
Public Shared Function EnumArrayToCSV(ByVal values() As System.Enum) As String
Dim result As Generic.List(Of String) = New Generic.List(Of String)
For i As Integer = 0 To values.GetUpperBound(0)
result.Add(Convert.ToInt32(values(i)))
Next i
Return String.Join(",", result.ToArray)
End Function
I realise that the arguement is incorrect as I am working with an array of enums. Ideally, I'd like to be working with a generic set of enum values.
Can anyone help?
Upvotes: 1
Views: 2910
Reputation: 416149
Public Shared Function CSVFromEnumValues(Of T)(ByVal values As IEnumerable(Of T)) As String
Dim sb As New StringBuilder()
Dim delimiter As String = ""
For Each item As T In values
sb.Append(delimiter).Append(Convert.ToInt32(item).ToString())
delimiter = ","
Next item
return sb.ToString()
End Function
Some notes on this code:
TypeFromType()
rather than TypeToType()
naming convention, because it places the types near the variable that contain them rather than the reverse. Upvotes: 4