Reputation: 15774
I am simply trying to spit out a string which aggregates a List's values into a NewLine delimited string.
<Extension()>
Public Function ToColumn(Of T)(ByVal source As IEnumerable(Of T)) As String
' assuming Aggregate(Of String) will be inefficient, using StringBuilder
Dim sb As New StringBuilder()
For Each val As T In source
sb.Append(val.ToString() & Environment.NewLine)
Next
Return sb.ToString()
End Function
This method will help while debugging to see the entire contents of a List, while ?source
only spits out the first 100 elements in the immediate window (maybe there is a different way to do this?). I just want to be able to copy it over to something like Excel quickly for analysis.
The problem is that although this method compiles, in usage, it is not recognized as an extension of List(of T) i.e.
Dim result As Int32()
Debug.Print(result.ToList().ToColumn())
' this line doesn't compile:
' 'toColumn' is not a member of 'System.Collections.Generic.List(Of Integer)'
I'd like to reuse this method on anything which I can box into an Object and get .ToString() (everything!), hence the generic aspect of it. I have seen many people add constraints to the generic T, i.e. Where T : Constraint
, but my constraint would be Object, as is the nature of this method, which doesn't compile.
My question is why isn't it recognized as an extension of List(Of Integer). Also, is what I want to achieve possible?
Upvotes: 2
Views: 4264
Reputation: 34846
Have you tried using an extension method on List(Of T)
instead of IEnumerable(Of T)
, like this:
<Extension()>
Public Function ToColumn(Of T)(ByVal source As List(Of T)) As String
' assuming Aggregate(Of String) will be inefficient, using StringBuilder
Dim sb As New StringBuilder()
For Each val As T In source
sb.Append(val.ToString() & Environment.NewLine)
Next
Return sb.ToString()
End Function
Upvotes: 2