Generic List

S

shapper

Hello,

How can I convert a Generic.List(Of String) to a single string where
all elements are separated by a comma?

My string would become:

"item1,item2,item3"

Thanks,

Miguel
 
G

Grant Merwitz

C# example

List<string> Strlist = new List<string>();

StrList.Add("1");
StrList.Add("2");
StrList.Add("3");

string SingleString = "";
foreach(string s in Strlist.ToArray())
SingleString += s + ",";

You can then either remove the last ","
or in the loop work out which is the first item or last
 
G

Guest

Howdy,

I'd would not recommend this approach as is inefficient (first copy to
array, and then string concatenation). This is much faster:

public static string ConcatList<T>(
System.Collections.Generic.IList<T> list, char separator)
{
System.Text.StringBuilder text =
new System.Text.StringBuilder();

for (int i = 0; i < list.Count; i++)
{
text.Append(list);
text.Append(separator);
}

if (text.Length > 0)
text.Length -= 1;

return text.ToString();
}
 
G

Grant Merwitz

thanks for a more efficient method.

I'll be sure to use that in future

Milosz Skalecki said:
Howdy,

I'd would not recommend this approach as is inefficient (first copy to
array, and then string concatenation). This is much faster:

public static string ConcatList<T>(
System.Collections.Generic.IList<T> list, char separator)
{
System.Text.StringBuilder text =
new System.Text.StringBuilder();

for (int i = 0; i < list.Count; i++)
{
text.Append(list);
text.Append(separator);
}

if (text.Length > 0)
text.Length -= 1;

return text.ToString();
}
--
Milosz


Grant Merwitz said:
C# example

List<string> Strlist = new List<string>();

StrList.Add("1");
StrList.Add("2");
StrList.Add("3");

string SingleString = "";
foreach(string s in Strlist.ToArray())
SingleString += s + ",";

You can then either remove the last ","
or in the loop work out which is the first item or last
 

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

Similar Threads

Generic List to String 0
Generic List to String 3
Generic List to Array 2
Retrieving and copying element from array 10
Generic List Order 0
String 3
Generic List. Remove duplicate 2
DataSet to Generic List 1

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,584
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top