Generic List

  • Thread starter Thread starter shapper
  • Start date Start date
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
 
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
 
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();
}
 
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
 
Back
Top