Generic List to String

S

shapper

Hello,

How can I transform a Generic List(Of String) to a string as follows:

"value1,value2,value3,value4, ..."

Thanks,
Miguel
 
T

Thomas Hansen

Hello,

How can I transform a Generic List(Of String) to a string as follows:

"value1,value2,value3,value4, ..."

Either:
string tmp = "";
foreach( string x in myGenericList )
{
tmp += x + ",";
}

OR....!
Do a search for LVK
(Lasse Vågsæther Karlsen open source project that solves all the
problems you ever thought you had regarding manipulating generic
collections... ;)


Thomas
 
G

Guest

Hi Shapper and Thomas,

I'd would not recommend this approach as is inefficient (string
concatenation). This is much faster:

Public Shared Function ConcatList(Of T)( _
ByVal list As System.Collections.Generic.IList(Of T), _
ByVal separator As Char) As String

Dim text As System.Text.StringBuilder = _
New System.Text.StringBuilder()

For i as Integer = 0 To list.Count - 1
text.Append(list(i))
text.Append(separator)
Next

If text.Length > 0 Then
text.Length = text.Length - 1
End If

Return text.ToString()
End Function


Hope this helps
 
C

Cowboy \(Gregory A. Beamer\)

Try:

//C#
StringBuilder builder = new StringBuilder();

for (int i=0;i<list.Count;i++)
{
if(i!=0)
builder.Append(",");

builder.Append(list);
}

return builder.ToString();

'VB.NET
Dim builder As New StringBuilder()

For (i as Integer = 0 to list.Count - 1)

If i <> 0 Then
builder.Append(",")
End If

builder.Append(list(i))

Next

return builder.ToString()

It avoids having to clip off the last item as Milosz has done.


--
Gregory A. Beamer
MVP; MCP: +I, SE, SD, DBA
http://gregorybeamer.spaces.live.com

*********************************************
Think outside the box!
*********************************************
 
G

Guest

Hi Gregory,

I did cliping to avoid if-ing in the loop (which I suspect for large counts
is slower than clipping).

Regards
--
Milosz


Cowboy (Gregory A. Beamer) said:
Try:

//C#
StringBuilder builder = new StringBuilder();

for (int i=0;i<list.Count;i++)
{
if(i!=0)
builder.Append(",");

builder.Append(list);
}

return builder.ToString();

'VB.NET
Dim builder As New StringBuilder()

For (i as Integer = 0 to list.Count - 1)

If i <> 0 Then
builder.Append(",")
End If

builder.Append(list(i))

Next

return builder.ToString()

It avoids having to clip off the last item as Milosz has done.


--
Gregory A. Beamer
MVP; MCP: +I, SE, SD, DBA
http://gregorybeamer.spaces.live.com

*********************************************
Think outside the box!
*********************************************
shapper said:
Hello,

How can I transform a Generic List(Of String) to a string as follows:

"value1,value2,value3,value4, ..."

Thanks,
Miguel
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top